June LeetCoding17 之 二维矩阵的dfs

首先将dfs代码贴出来。然后再结合leetcode200 Number of Islands 和 leetcode130 Surrounded Regions 这两道题看具体应用

dfs代码如下:

    public void dfs(char[][] grid, int i, int j){
        if(i < 0 || j < 0 || i >= grid.length || j >= grid[0].length) return;
        if(grid[i][j] == '1'){
            grid[i][j] = '0';
            dfs(grid, i-1, j);
            dfs(grid, i+1, j);
            dfs(grid, i, j-1);
            dfs(grid, i, j+1);
        }
    }

 

leetcode200 是在下面这个矩阵中找有几个‘1’组成的联通分量。对矩阵进行深度搜索,将相连的1都设为0。记录进行了几次深度搜索,即有几个连通分量。

11110
11010
11000
00000
class Solution {
    public int numIslands(char[][] grid) {
        if(grid == null || grid.length == 0)
            return 0;
        int res = 0;
        for(int i = 0; i < grid.length; i++){
            for(int j = 0; j < grid[0].length; j++){
                if(grid[i][j] == '1'){
                    res++;
                    dfs(grid, i, j);
                }
            }
        }
        return res;
    }
    public void dfs(char[][] grid, int i, int j){
        if(i < 0 || j < 0 || i >= grid.length || j >= grid[0].length) return;
        if(grid[i][j] == '1'){
            grid[i][j] = '0';
            dfs(grid, i-1, j);
            dfs(grid, i+1, j);
            dfs(grid, i, j-1);
            dfs(grid, i, j+1);
        }
    }
}

 

leetcode130 同样用到了二维矩阵的深度搜索。

class Solution {
    public void solve(char[][] board) {
        if(board.length <= 2 || board.length <= 2) return;
        int m = board.length;
        int n = board[0].length;
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                if((i == 0 || i == board.length-1 || j == 0 || j == board[0].length-1)&&board[i][j] == 'O')
                    dfs(board, i, j);
            }
        }
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                if(board[i][j] == 'O') board[i][j] = 'X';
                if(board[i][j] == '$') board[i][j] = 'O';
            }
        }
    }
    public void dfs(char[][] board, int i, int j){
        if(i < 0 || j < 0 || i >= board.length || j >= board[0].length) return;
        if(board[i][j] == 'O'){
            board[i][j] = '$';
            dfs(board, i-1, j);
            dfs(board, i+1, j);
            dfs(board, i, j-1);
            dfs(board, i, j+1);
        }
    }
}

 

posted @ 2020-06-17 20:36  yawenw  阅读(261)  评论(0编辑  收藏  举报