The original problem says that it should be counted the number of islands (connected entities of 1 into a sea of 0).
For example:
0001
1001
0110
should return 3 becasue there are 3 islands.
I managed to get a solution to this:
function countIslands(A) {
const row = A.length;
const col = A[0].length;
const search = (row, col, A) => {
if(row < 0 || col < 0 || row > A.length - 1 || col > A[row].length - 1 || A[row][col] === 0) {
return;
}
A[row][col] = 0;
search(row-1,col,A);
search(row,col-1,A);
search(row+1,col,A);
search(row,col+1,A);
}
let count = 0;
A.forEach((row, index) => {
row.forEach((value, indexI) => {
if(value === 1) {
search(index, indexI, A);
count++;
}
})
})
return count;
}
it works fine. But is it a way to change it (ideally not a lot of changes) to make it able to count countries?
For example:
1122
1223
5521
should return 5 because there are 5 entities in the matrix.
You could hand over the actual value and look only for adjacent same values.
I add some visualation for the found islands/countries.
function countIslands(A) {
const row = A.length;
const col = A[0].length;
const search = (row, col, A, value) => {
if (row < 0 || col < 0 || row >= A.length || col >= A[row].length || A[row][col] !== value) {
return;
}
A[row][col] = 0;
search(row - 1, col, A, value);
search(row, col - 1, A, value);
search(row + 1, col, A, value);
search(row, col + 1, A, value);
}
let count = 0;
A.forEach((row, index) => {
row.forEach((value, indexI) => {
if (value !== 0) {
A.forEach(a => console.log(...a));
console.log('');
search(index, indexI, A, value);
count++;
}
})
})
A.forEach(a => console.log(...a))
return count;
}
console.log(countIslands([[1, 1, 2, 2], [1, 2, 2, 3], [5, 5, 2, 1]]));
.as-console-wrapper { max-height: 100% !important; top: 0; }