欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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; 

    }
   
}

 

相关标签: leetcode dfs