130. Surrounded Regions (DFS)

经过一个月的倦怠期,我徐汉三又回来啦!FLAG每天至少一道题坚持到秋招offer!!!

今天的题目是DFS思想。https://leetcode.com/problems/surrounded-regions/

Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.

A region is captured by flipping all 'O's into 'X's in that surrounded region.

Example:

X X X X
X O O X
X X O X
X O X X

After running your function, the board should be:

X X X X
X X X X
X X X X
X O X X

Explanation:

Surrounded regions shouldn’t be on the border, which means that any 'O' on the border of the board are not flipped to 'X'. Any 'O' that is not on the border and it is not connected to an 'O' on the border will be flipped to 'X'. Two cells are connected if they are adjacent cells connected horizontally or vertically.

意思就是边界上的‘O’以及和边界上的‘O’相邻的‘O’ 可以保留,其余的转成‘X’.

所以可以从四个边界出发进行深度优先遍历,标记和边界上‘O’相邻的“O”为‘*’;

然后依次遍历所有点,将“*”变成‘O’,其他的都是‘X’.

注意不要忘记边界条件判断。

class Solution {
    private int[][] directions = {{0,1},{0,-1},{1,0},{-1,0}};
    
    public void solve(char[][] board) {
        if(board==null || board.length==0)
            return;
        for(int i=0;i<board.length;i++){
            dfs(board, i, 0);
            dfs(board, i, board[0].length-1);
        }
        for(int i=0;i<board[0].length;i++){
            dfs(board, 0, i);
            dfs(board, board.length-1, i);
        }
        for(int i=0;i<board.length;i++){
            for(int j=0;j<board[0].length;j++){
                if(board[i][j]=='*')
                    board[i][j]='O';
                else
                    board[i][j]='X';
            }
        }
    }
    public void dfs(char[][] board, int i, int j){
        if(i<0 || i>= board.length || j<0 || j>=board[0].length || board[i][j]!='O')
            return;
        board[i][j]='*';
        for(int[] dir:directions){
            dfs(board, i+dir[0], j+dir[1]);
        }
    }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值