-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
✅200. 岛屿数量 #40
Comments
解题思路:
/**
* @param {character[][]} grid
* @return {number}
*/
var numIslands = function (grid) {
let count = 0;
function dfs(row, col) {
if (
row < 0 ||
row >= grid.length ||
col < 0 ||
col >= grid[0].length ||
grid[row][col] === "0"
) {
return;
}
grid[row][col] = "0";
dfs(row + 1, col);
dfs(row - 1, col);
dfs(row, col + 1);
dfs(row, col - 1);
}
for (let row = 0; row < grid.length; row++) {
for (let col = 0; col < grid[0].length; col++) {
if (grid[row][col] === "1") {
count++;
dfs(row, col);
}
}
}
return count;
}; |
深度优先遍历
function helper(grid, x, y, rowLen, colLen) {
if (x < 0 || y < 0 || x > rowLen - 1 || y > colLen - 1 || grid[x][y] == '0') return;
grid[x][y] = '0';
helper(grid, x - 1, y, rowLen, colLen);
helper(grid, x + 1, y, rowLen, colLen);
helper(grid, x, y - 1, rowLen, colLen);
helper(grid, x, y + 1, rowLen, colLen);
}
/**
* @param {character[][]} grid
* @return {number}
*/
var numIslands = function(grid) {
// DFS
let isLand = 0;
const rowLen = grid.length;
if (rowLen === 0) return 0;
const colLen = grid[0].length;
for (let x = 0; x < rowLen; x++) {
for (let y = 0; y < colLen; y++) {
if (grid[x][y] == '1') {
helper(grid, x, y, rowLen, colLen);
isLand++;
}
}
}
return isLand;
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
200. 岛屿数量
给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。
示例 1:
示例 2:
解释: 每座岛屿只能由水平和/或竖直方向上相邻的陆地连接而成。
The text was updated successfully, but these errors were encountered: