leetcode-cn.com/problems/nu…
Answer:
- So let’s say we have a coordinate, according to the description
grid[i][j] === '1'
, so from it, you keep moving the coordinates up, down, left, and right, and as long as the value of the coordinates is still 1, all the points you encounter belong to the same island. - We can use two nested for loops to traverse the current grid. If we encounter one coordinate of 1, we encounter an island, and then we increment the number of islands by one.
- At the same time, DFS is used to set all adjacent coordinates of the current coordinate to 0, that is, sink the island.
- Once the recursion is complete, the grid continues to be traversed, and the coordinates of the single remaining islands have been zeroed out and will not be counted twice.
- When the sermon was over, we knew the number of islands.
/ * * *@param {character[][]} grid
* @return {number}* /
var numIslands = function (grid) {
let count = 0; // Count islands
// Iterate over the grid rows
for (let i = 0; i < grid.length; i++) {
// Iterate over the grid columns
for (let j = 0; j < grid[i].length; j++) {
// When 1 is encountered, an island is encountered
if (grid[i][j] === '1') {
// Increment the island count by 1
count++;
// Use DFS to change all 1s in the current coordinate to 0, i.e. sink the entire island
// After all the coordinates of the island are changed to 0, subsequent traversals will not encounter the 1 of the island, ensuring that there is no double counting of the islandsinkIsland(i, j); }}}// Use DFS to sink the current island by changing all coordinates of the current island to 0
function sinkIsland(i, j) {
if (
// Stop sinking when the coordinates are outside the grid
i < 0 ||
j < 0 ||
i >= grid.length ||
j >= grid[i].length ||
// Stop sinking when water hits
grid[i][j] === '0'
) {
return;
}
// Change the current coordinate value to 0
grid[i][j] = '0';
// Continue to modify the island value by moving the coordinates up, down, left, and right
sinkIsland(i - 1, j);
sinkIsland(i, j - 1);
sinkIsland(i + 1, j);
sinkIsland(i, j + 1);
}
// Return the number of islands counted
return count;
};
Copy the code