LeetCode learning record

Keywords: Programming

Given a two-dimensional grid consisting of '1' (land) and '0' (water), the number of islands is calculated. An island is surrounded by water, and it is connected by adjacent land horizontally or vertically. You can assume that all four sides of the mesh are surrounded by water.

Example 1:

Input:
11110
11010
11000
00000

Output: 1

Example 2:

Input:
11000
11000
00100
00011

Output: 3

Solution idea: in addition, create a 2D array to record the land and its boundary, when encountering an array that is 1 (land) in the original 2D array and 0 (not accessed) in the new 2D array. It's a new island.

The code is as follows:

class Solution {
    public int numIslands(char[][] grid) {
        int count=0;
         if(grid.length==0){
            return 0;
        }
        char[][] visit=new char[grid.length][grid[0].length];
        for(int i=0;i<grid.length;i++){
            for(int j=0;j<grid[0].length;j++ ){
                if(visit[i][j]!='1'){
                    if(grid[i][j]=='1'){//Root + 1
                        count++;
                        /*System.out.print(i+" " );
                        System.out.print(j+" ");
                        System.out.println(visit[i][j]);*/
                    }
                }
            dfsvisit(grid,visit,i,j);//Traverse all the points connected to the root node at one time
            }
        }
   /* for(int i=0;i<grid.length;i++){
            for(int j=0;j<grid[0].length;j++ ){
              System.out.print(visit[i][j]);
            }
            System.out.println();
            }*/
    return count;
    }
    
  public static void dfsvisit(char[][] grid,char[][] visit,int i,int j){
      if(i<0||i>grid.length-1||j<0||j>grid[0].length-1){//Cross border
          return ;
      }else if(grid[i][j]=='0'){//Ocean
          return ;
      }else if(visit[i][j]=='1'){//It means that this place is connected with the mainland
          return ;
      }else{
          visit[i][j]='1';
          dfsvisit(grid,visit,i+1,j);//Step down
          dfsvisit(grid,visit,i-1,j);//Take a step up
          dfsvisit(grid,visit,i,j+1);//Take a step to the right
          dfsvisit(grid,visit,i,j-1);//Take a step to the right
      }
  }
}

public class Main{
    public static void main(String[] args){
        char grid[][]={{'1','0','1','1','1'},{'1','0','1','0','1'},{'1','1','1','0','1'}};
        Solution solve=new Solution();
        int num=solve.numIslands(grid);
        System.out.println(num);
    }
}

 

Posted by abhi_elementx on Fri, 13 Dec 2019 13:48:08 -0800