Search number of connected components (the DFS) --- matrix

The number of connected components of the matrix

200. Number of Islands (Medium)

Input:
11000
11000
00100
00011

Output: 3

Subject description:

  Given a matrix, the number of required components Unicom matrix.

Analysis of ideas:

  Traversing to a 1 in the matrix, and then connected to all 1 1 0 are assigned, and then view the matrix 1 can appear several times such, that the number of components Unicom.

Code:

public int numsIslands(char[][]grid){
    if(grid==null||grid.length==0)
        return 0;
    int m=grid.length;
    int n=grid[0].length;
    int res=0;
    for(int i=0;i<m;i++){
        for(int j=0;j<n;j++){
            if(grid[i][j]!='0'){
                dfs(grid,i,j);
                res++;
            }
        }
    }
    return res;
}
public void dfs(char[][]grid,int r,int c){
    int [][]direction={{0,1},{0,-1},{1,0},{-1,0}};
    if(r<0||r>=grid.length||c<0||c>=grid[0].length||grid[r][c]=='0')
       return ;
    grid[r][c]='0';
    for(int []d:direction){
        dfs(grid,r+d[0],c+d[1]);
    }
}

Guess you like

Origin www.cnblogs.com/yjxyy/p/11110138.html