1. 首页
  2. 软件开发
  3. day-22 岛屿数量

day-22 岛屿数量

  • 发布于 2024-09-26
  • 1 次阅读


参考了答案。。。。。。

思路:深度优先遍历,对每个是陆地且未曾访问过的位置进行dfs,每进行一次,岛屿数量加一

code:

class Solution {

    private static final int[][] dir = {
   {
   -1, 0}, {
   0, -1}, {
   1, 0}, {
   0, 1}};
    private boolean[][] visited;
    private int rows;
    private int cols;
    private char[][] grid;

    public int numIslands(char[][] grid) {

        rows=grid.length;
        if(rows==0){

            return 0;
        }
        cols=grid[0].length;

        this.grid=grid;
        visited=new boolean[rows][cols];
        int count=0;
        for(int i=0;i<rows;i++){

            for(int j=0;j<cols;j++){

                if(!visited[i][j]&&grid[i][j]=='1'){

                    dfs(i,j);
                    count++;
                }
            }
        }
        return count;
    }

    public void dfs(int i,int j){

        visited[i][j]=true;
        for(int k=0;k<4;k++){

            int newx=i+dir[k][0];
            int newy=j+dir[k][1];
            if(0<=newx&&newx<rows&&0<=newy&&newy<cols&&!visited[newx][newy]&&grid[newx][newy]=='1'){

                dfs(newx,newy);
            }
        }
    }
}

原文链接: https://blog.csdn.net/qq_53568730/article/details/136790821