岛屿数量
给你一个由 '1'
(陆地)和 '0'
(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。
- 示例 1:
输入:grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
输出:1
- 示例 2:
输入:grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
输出:3
javascript
/**
* @param {character[][]} grid
* @return {number}
*/
var numIslands = function (grid) {
const m = grid.length
const n = grid[0].length
let landCount = 0;
function expandLand(row, col) {
const isLand = grid[row][col]
if (isLand !== '1') return
grid[row][col] = '-1' // 访问过的土地,不可再访问
if (row > 0) {
// 上
expandLand(row - 1, col)
}
if (row < m - 1) {
// 下
expandLand(row + 1, col)
}
if (col > 0) {
// 左
expandLand(row, col - 1)
}
if (col < n - 1) {
// 右
expandLand(row, col + 1)
}
}
for (let r = 0; r < m; r++) {
for (let c = 0; c < n; c++) {
// 如果当前位置是陆地,则为新陆地
const isLand = grid[r][c]
// 访问周边陆地
if (isLand === '1') {
landCount += 1
expandLand(r, c) // 扩张联通的陆地,全部置为已访问
}
}
}
return landCount
};
解题思路
遍历所有位置,首次遇到值为'1'陆地
时,此时岛屿数量+1,然后从上下左右四个方向寻找相连通的陆地,并标识为'-1'已访问状态
,再寻找下一个陆地就不会重复了