Leetcode Surrounded Regions

本文介绍了一种使用深度优先搜索(DFS)算法解决二维棋盘中被X包围的O型区域捕获问题的方法。通过首先将边缘上的O标记为Y,再将未被标记的O转换为X,最后将Y转换回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



通过DFS将与边缘O直接相连的O设置为Y,然后在进行遍历board,将O设置为X,将Y设置为O


代码如下:

class Solution {
public:
    class point
    {
        public:
        int x;
        int y;
        point(int i,int j)
        {
            x=i;
            y=j;
        }
    };
    
    void solve(vector<vector<char>>& board) {
        if(board.empty())
            return;
        int m = board.size();
        int n = board[0].size();
        queue<point*> data;
       
        for(int i=0;i<m;i++)
            for(int j=0;j<n;j++)
            {
                if(j==0||j==n-1||i==0||i==m-1)
                {
                    if(board[i][j] == 'O')
                    {
                        board[i][j]  = 'Y';
                        data.push(new point(i,j));
                    }
                }
            }
        
        while(!data.empty())
        {
            point* now = data.front();
            data.pop();
            int x = now->x;
            int y = now->y;
            
            board[x][y]  = 'Y';
            
            if(x+1<m && board[x+1][y] == 'O' )
                data.push(new point(x+1,y));
            
            if(x-1>=0  && board[x-1][y] == 'O' )
                data.push(new point(x-1,y));
            
            if(y+1<n && board[x][y+1] == 'O' )
                data.push(new point(x,y+1));
            
            if(y-1>=0 && board[x][y-1] == 'O' )
                data.push(new point(x,y-1));
        }
        
        for(int i=0;i<m;i++)
            for(int j=0;j<n;j++)
            {
                if(board[i][j] == 'Y')
                    board[i][j] = 'O';
                else if(board[i][j] == 'O')
                    board[i][j] = 'X';
            }
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值