【LeetCode】#130被围绕的区域(Surrounded Regions)

【LeetCode】#130被围绕的区域(Surrounded Regions)

题目描述

给定一个二维的矩阵,包含 ‘X’ 和 ‘O’(字母 O)。
找到所有被 ‘X’ 围绕的区域,并将这些区域里所有的 ‘O’ 用 ‘X’ 填充。

示例

X X X X
X O O X
X X O X
X O X X
运行你的函数后,矩阵变为:
X X X X
X X X X
X X X X
X O X X
解释:
被围绕的区间不会存在于边界上,换句话说,任何边界上的 ‘O’ 都不会被填充为 ‘X’。 任何不在边界上,或不与边界上的 ‘O’ 相连的 ‘O’ 最终都会被填充为 ‘X’。如果两个元素在水平或垂直方向相邻,则称它们是“相连”的。

Description

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.

解法

class Solution {
    public void solve(char[][] board) {
        if(board.length==0)
            return;
        int row = board.length;
        int col = board[0].length;
        for(int i=0; i<row; i++){
            if(board[i][0]=='O')
                helper(board, i, 0);
            if(board[i][col-1]=='O')
                helper(board, i, col-1);
        }
        for(int i=0; i<col; i++){
            if(board[0][i]=='O')
                helper(board, 0, i);
            if(board[row-1][i]=='O')
                helper(board, row-1, i);
        }
        for(int i=0; i<row; i++){
            for(int j=0; j<col; j++){
                if(board[i][j]=='O')
                    board[i][j] = 'X';
                else if(board[i][j]=='*')
                    board[i][j] = 'O';
            }
        }
    }
    public static void helper( char[][] board , int x, int y ){
        int[][] nums = {{0,1},{0,-1},{1,0},{-1,0}};
        Queue<Integer[]> queue = new LinkedList<>();
        Integer[] integers = {x,y};
        queue.offer(integers);
        board[x][y] = '*';
        while ( queue != null && queue.size() != 0){
            Integer[] temp = queue.poll();
            for (int i = 0; i < 4; i++) {
                Integer newX = temp[0]+nums[i][0];
                Integer newY = temp[1]+nums[i][1];
                if (newX < 0 || newX >= board.length || newY < 0 || newY >= board[0].length) 
                    continue;
                if (board[newX][newY] == 'O'){
                    board[newX][newY] = '*';
                    Integer[] t = {newX, newY};
                    queue.offer(t);
                }
            }
        }
 
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值