Leetcode of depth-first search (DFS) Thematic -200 The number of islands (Number of Islands)
Given the a '1' (land) and '0' two-dimensional grid (water) composition, the number of islands is calculated. An island surrounded by water, and it is through the horizontal or vertical direction is connected to each adjacent land. You can assume that the water surrounding the four sides of the grid are. Example 1 : Input: 11110 11010 11000 00000 Output: 1 Example 2 : Input: 11000 11000 00100 00011 Output: 3
Analysis: This problem also seek communication block compared to 130. The area (Surrounded Regions) surrounded by a lot less restrictions title, the same is introduced VIS, four directions from the point search.
class Solution { int vis[][] = null; int dirx[] = {0,0,1,-1}; int diry[] = {1,-1,0,0}; public int numIslands(char[][] grid) { if(grid==null || grid.length==0){ return 0; } int years = 0 ; vis = new int[grid.length][grid[0].length]; for(int i=0;i<grid.length;i++){ for(int j=0;j<grid[0].length;j++){ if(grid[i][j]=='1' && vis[i][j]!=1){ years ++ ; dfs(grid,i,j); } } } return years; } public void dfs(char[][] board,int x,int y){ if(x<0 || y<0 || x>=board.length || y>=board[0].length || board[x][y]=='0' || vis[x][y]==1){ return; } vis[x][y] = 1; for(int i=0;i<4;i++){ int xx = x+dirx[i]; int yy = y+diry[i]; dfs(board,xx,yy); } } }