[LeetCode] Surrounded Regions

Given a 2D board containing 'X' and 'O', capture allregions surrounded by 'X'.

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

For example,


Afterrunning your function, the board should be: 


分析:

         如果某个’O’没有被捕获,那么它有两种情况,位于边界处,或者与边界处的’O’连通。所以我们可以从四个边界上的’O’开始深度搜索,它能到达的’O’都标记为’G’。四个边界都处理完后,再扫描一遍数组,将标记为’G’的都还原为’O’,标记为’O’的更新为’X’。

         代码如下:

 

class Solution {
public:
    void solve(vector<vector<char>> &board) {
        boundx = board.size();
        if (boundx == 0)
            return;
        boundy = board[0].size();
		for (int j = 0; j < boundy; ++j) {
			if (board[0][j] == 'O') {
				DFS(0, j, board);
			}
			if (board[boundx-1][j] == 'O') {
				DFS(boundx-1, j, board);
			}
		}
		for (int i = 1; i < boundx - 1; ++i) {
			if (board[i][0] == 'O') {
				DFS(i, 0, board);
			}
			if (board[i][boundy-1] == 'O') {
				DFS(i, boundy-1, board);
			}
		}
        for (int i = 0; i < boundx; ++i) {
            for (int j = 0; j < boundy; ++j) {
                if (board[i][j] == 'O') {
                    board[i][j] = 'X';
                }
                else if (board[i][j] == 'G')
                    board[i][j] = 'O';
            }
        }
        return;
     }
private:
    void DFS(int px, int py, vector<vector<char>> &board) {          
            int tmpx = px, tmpy = py;
            for (int i = 0; i < 4; ++i) {
                px += next[i][0];
                py += next[i][1];
                if (px < 0 || px >= boundx || py >= boundy || py < 0) {
                    board[tmpx][tmpy] = 'G';
                }
                else if (board[px][py] == 'O') {
                    board[px][py] = 'G';
                    DFS(px, py, board);
                }
                px = tmpx;
                py = tmpy;
            }
    }
    int boundx;
    int boundy;
    const int next[4][2] = {
                                {-1, 0},//up
                                {0, 1}, //right
                                {1, 0}, //down
                                {0, -1} //left
                            };
    
};

Question:但是上面的代码并不能AC,错误原因是RuntimeError,起初以为可能是给的测试数据不等长,不能构成一个二维数组,所以把该测试用例在自己电脑上跑了一遍,运行没有问题,答案是正确的。不明白LeetCode上是什么情况导致的Runtime Error。请知道的朋友多多指教。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值