LeetCode力扣之130. Surrounded Regions

本文介绍了解决LeetCode 130题目的算法实现:包围区域。通过BFS遍历边界上的'O'并标记,最终将未被标记的'O'转化为'X',实现对被包围'O'区域的捕获。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

For 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

package leetCode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * Created by lxw, liwei4939@126.com on 2018/3/26.
 */
class Point{
    int x;
    int y;
    public Point(int x, int y){
        this.x = x;
        this.y = y;
    }
}
public class L130_SurroundedRegions {

    public void solve(char[][] board){
        if (board.length == 0){
            return;
        }
        int row = board.length;
        int col = board[0].length;
        Queue<Point> queue = new LinkedList<>();

        for (int r = 0; r < row; r++){
            if (board[r][0] == 'O'){
                board[r][0] = '+';
                queue.add(new Point(r, 0));
            }
            if (board[r][col -1] == 'O'){
                board[r][col-1] = '+';
                queue.add(new Point(r, col-1));
            }
        }

        for (int c= 0; c < col; c++){
            if (board[0][c] == 'O'){
                board[0][c] = '+';
                queue.add(new Point(0, c));
            }
            if (board[row-1][c] == 'O'){
                board[row-1][c] = '+';
                queue.add(new Point(row-1, c));
            }
        }

        while (!queue.isEmpty()){
            Point p = queue.poll();
            int r = p.x;
            int c = p.y;
            if (r-1 >= 0 && board[r-1][c] == 'O'){
                board[r-1][c] = '+';
                queue.add(new Point(r-1, c));
            }
            if (r+1 < row && board[r+1][c] == 'O'){
                board[r+1][c] ='+';
                queue.add(new Point(r+1, c));
            }
            if (c-1 >= 0 && board[r][c-1] == 'O'){
                board[r][c-1] = '+';
                queue.add(new Point(r, c-1));
            }
            if (c+1 < col && board[r][c+1] == 'O'){
                board[r][c+1] = '+';
                queue.add(new Point(r,c+1));
            }
        }

        for (int i = 0; i<row; i++){
            for (int j=0; j<col; j++){
                if (board[i][j] == 'O') board[i][j] = 'X';
                if (board[i][j] == '+') board[i][j] = 'O';
            }
        }

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值