Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input: 11110 11010 11000 00000 Output: 1
Example 2:
Input: 11000 11000 00100 00011 Output: 3
题目链接:https://leetcode.com/problems/number-of-islands/
题目分析:DFS
2ms,时间击败86.6%
class Solution {
public int[] dx = {1, 0, -1, 0};
public int[] dy = {0, 1, 0 ,-1};
public void DFS(int x, int y, int n, int m, char[][] grid, boolean[][] vis) {
vis[x][y] = true;
for (int i = 0; i < 4; i++) {
int xx = x + dx[i];
int yy = y + dy[i];
if (xx >= 0 && yy >= 0 && xx < n && yy < m && grid[xx][yy] == '1' && !vis[xx][yy]) {
DFS(xx, yy, n, m, grid, vis);
}
}
}
public int numIslands(char[][] grid) {
int n = grid.length;
if (n == 0) {
return 0;
}
int m = grid[0].length;
int ans = 0;
boolean[][] vis = new boolean[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] == '1' && !vis[i][j]) {
DFS(i, j, n, m, grid, vis);
ans++;
}
}
}
return ans;
}
}

本文详细解析了LeetCode上的一道经典问题——岛屿数量,通过深度优先搜索(DFS)算法,有效地解决了二维网格中岛屿数量的计算问题。文章提供了完整的代码实现,包括递归的DFS函数和主函数,用于遍历网格并标记已访问过的陆地,最终返回岛屿的总数。
962

被折叠的 条评论
为什么被折叠?



