LeetCode200.岛屿数量
程序员文章站
2022-05-20 20:12:03
...
题目链接:https://leetcode-cn.com/problems/number-of-islands
class Solution {
private int n;
private int m;
public void dfs(boolean[][] visited,char[][] grid,int i,int j){
if(i>=n||j>=m||i<0||j<0||visited[i][j]==true) return;
visited[i][j]=true;
if(grid[i][j]=='1'){
dfs(visited,grid,i,j+1);
dfs(visited,grid,i+1,j);
dfs(visited,grid,i-1,j);
dfs(visited,grid,i,j-1);
}
}
public int numIslands(char[][] grid) {
if(grid==null|grid.length==0) return 0;
n=grid.length;
m=grid[0].length;
boolean[][] visited=new boolean[n][m];
int number=0;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(!visited[i][j]&&grid[i][j]=='1'){
dfs(visited,grid,i,j);
number++;
}
}
}
return number;
}
}
上一篇: python 深度优先与广度优先
下一篇: 走迷宫算法 用python实现