8-3 深度优先

1、dfs算法模板

    void dfs(char[][] grid,int x,int y){
        //递归出口
        if(x<0|| y<0 || x>=grid.length || y>=grid[0].length || grid[x][y]=='0'){
            return;
        }

        //标记访问
        grid[x][y]='0';

        //四个方向探索
        dfs(grid,x,y-1);
        dfs(grid,x-1,y);
        dfs(grid,x,y+1);
        dfs(grid,x+1,y);

    }

2、例题:岛屿的数量

class Solution{
    public int numIslands(char[][] grid){
        if(grid==null || grid.length==0){
            return 0;
        }

        int m=grid.length,n=grid[0].length,count=0;
        for(int i=0;i=grid.length || y>=grid[0].length || grid[x][y]=='0'){
            return;
        }

        grid[x][y]='0';
        dfs(grid,x,y-1);
        dfs(grid,x-1,y);
        dfs(grid,x,y+1);
        dfs(grid,x+1,y);

    }
}

 

你可能感兴趣的:(数据结构与算法)