Problem solving | #Number of islands#
topic link
Topic description
Time limit: 1 second Space limit: 256M
describe
Given a 01 matrix, 1 represents land, 0 represents ocean, if two 1s are adjacent, then the two 1s belong to the same island. We only consider up, down, left and right as adjacent.
Island: Adjacent land can form an island (adjacent: up, down, left and right) Determine the number of islands.
E.g:
enter
[
[1,1,0,0,0],
[0,1,0,1,1],
[0,0,0,1,1],
[0,0,0,0,0],
[0,0,1,1,1]
]
The corresponding output is
3
Example 1
enter:
[[1,1,0,0,0],[0,1,0,1,1],[0,0,0,1,1],[0,0,0,0,0],[0,0,1,1,1]]
return value:
3
Example 2
enter:
[[0]]
return value:
0
Example 3
enter:
[[1,1],[1,1]]
return value:
1
Remark:
01 Matrix range <=200*200
Problem solving ideas
A very typical dyeing method, perform dfs on each point, fully dye the adjacent points with a value of 1, and use sum to record the current dyeing value.
In short, the first island is fully stained as -1, the second island is fully stained as -2, and finally the inverse of the largest negative number is the correct answer.
Using a dfs will do the trick.
problem solving code
/**
* 判断岛屿数量
* @param grid string字符串型二维数组
* @return int整型
*/
function solve(grid) {
// write code here
// grid = [[1, 1, 0, 0, 0], [0, 1, 0, 1, 1], [0, 0, 0, 1, 1], [0, 0, 0, 0, 0], [0, 0, 1, 1, 1]];
let col = grid.length;
let row = grid[0].length;
let sum = 0;
let dfs = (x, y) => {
if (grid[x][y] == 1) {
grid[x][y] = sum;
}
let tox = x + 1;
let toy = y;
if (tox >= 0 && tox < col && toy >= 0 && toy < row && grid[tox][toy] == 1) {
dfs(tox, toy);
}
tox = x - 1;
toy = y;
if (tox >= 0 && tox < col && toy >= 0 && toy < row && grid[tox][toy] == 1) {
dfs(tox, toy);
}
tox = x;
toy = y + 1;
if (tox >= 0 && tox < col && toy >= 0 && toy < row && grid[tox][toy] == 1) {
dfs(tox, toy);
}
tox = x;
toy = y - 1;
if (tox >= 0 && tox < col && toy >= 0 && toy < row && grid[tox][toy] == 1) {
dfs(tox, toy);
}
return;
}
for (let i = 0; i < col; i++) {
for (let j = 0; j < row; j++) {
if (grid[i][j] == 1) {
sum--;
dfs(i, j);
}
}
}
sum = sum < 0 ? -sum : sum;
return sum;
}