题目:
200. 岛屿数量
题解:
典型的dfs模板题,注意一下访问控制条件即可。
代码:
public class code200 {
public static int numIslands(char[][] grid) {
if(grid.length == 0)
{
return 0;
}
int m = grid.length;
int n = grid[0].length;
boolean visited[][] = new boolean[m][n];
int count = 0;
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
if(grid[i][j] == '1' && !visited[i][j])
{
dfs(i, j, m, n, grid, visited);
count++;
}
}
}
return count;
}
public static void dfs(int i, int j, int m, int n, char grid[][], boolean visited[][])
{
if(i < 0 || i >= m || j < 0 || j >= n || grid[i][j] != '1' || visited[i][j])
{
return;
}
visited[i][j] = true;
dfs(i + 1, j, m, n, grid, visited);
dfs(i - 1, j, m, n, grid, visited);
dfs(i, j + 1, m, n, grid, visited);
dfs(i, j - 1, m, n, grid, visited);
}
public static void main(String[] args) {
char[][] grid1 = {
{'1', '1', '1', '1', '0'},
{'1', '1', '0', '1', '0'},
{'1', '1', '0', '0', '0'},
{'0', '0', '0', '0', '0'}};
int res1 = numIslands(grid1);
System.out.println(res1);
char[][] grid2 = {
{'1', '1', '0', '0', '0'},
{'1', '1', '0', '0', '0'},
{'0', '0', '1', '0', '0'},
{'0', '0', '0', '1', '1'}};
int res2 = numIslands(grid2);
System.out.println(res2);
}
}
参考:
- 岛屿数量
- DFS + BFS + 并查集(Python 代码、Java 代码)
- 朴实无华的深度优先遍历(最简单最直接c++)
- 深度优先搜索,希望大家喜欢