leetcode130 - Surrounded Regions - medium

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 X X X
X O O X -> X X X X
X X O X X X X X
X O X X X O X X

 

BFS。
问题转换:问题是找被X包围在内保护起来的O,正向找外界碰不到的O不好找,那就反向转化为找外界能连通到的O。那如果对边缘一圈的O做BFS,碰到的O肯定都是能连到地图外的O,那就标记为‘W’(灌水)。最后再遍历一次地图,让所有被灌水的回到‘O’,其他的都归为‘X’即可。
写一个某一个O向四周不断bfs标记其他O的子函数。主函数里对上下左右四条边的O进行bfs即可(bfs里隐式让看到非O就返回退出,能让主函数更简洁)。
细节:棋盘题进行上下左右移动可以借助int[] dx = {0, -1, 0, 1}; int[] dy = {-1, 0, 1, 0}; ,之后for(4) {newX = x + dx[i], newY = y + dy[i]}来做。

 

实现:

class Solution {
    public void solve(char[][] board) {
        
        if (board == null || board.length == 0 || board[0].length == 0) {
            return;
        }
        
        for (int i = 0; i < board.length; i++) {
            bfs(board, i, 0);
            bfs(board, i, board[0].length - 1);
        }
        
        for (int j = 0; j < board[0].length; j++) {
            bfs(board, 0, j);
            bfs(board, board.length - 1, j);
        }
        
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (board[i][j] == 'W') {
                    board[i][j] = 'O';
                } else if (board[i][j] == 'O') {
                    board[i][j] = 'X';
                }
            }
        }
    }
    
    private void bfs(char[][] board, int x, int y) {
        
        if (board[x][y] != 'O') {
            return;
        }
        
        board[x][y] = 'W';
        int[] dx = {0, 1, 0, -1};
        int[] dy = {1, 0, -1, 0};
        Queue<Integer> qx = new LinkedList<>();
        Queue<Integer> qy = new LinkedList<>();
        
        qx.offer(x);
        qy.offer(y);
        while (!qx.isEmpty()) {
            int cx = qx.poll();
            int cy = qy.poll();
            for (int i = 0; i < 4; i++) {
                int nx = cx + dx[i];
                int ny = cy + dy[i];
                if (nx >= 0 && nx < board.length && ny >= 0 
                    && ny < board[0].length && board[nx][ny] == 'O') {
                    board[nx][ny] = 'W';
                    qx.offer(nx);
                    qy.offer(ny);
                }
            }
        }
    }
}

 

转载于:https://www.cnblogs.com/jasminemzy/p/9644257.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值