码迷,mamicode.com
首页 > 其他好文 > 详细

Surrounded Regions -- leetcode

时间:2015-05-24 13:03:25      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:bfs   leetcode   

Given a 2D board containing ‘X‘ and ‘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

基本思路:

以矩阵最外层的每个点,如果其值为‘O‘,进行bfs搜索,并将访问过的结点,从‘O‘,变为其他字符‘1‘,以作为标记。

1.是作为已访问标记。2.是作为连通标记。

当对外层所有节点完成上述操作后的。

再进行一次全体扫描,其中,如果值仍为‘O‘,说明这些是被‘X‘包围的结点,不与边界上的‘O‘联通。则将其置为‘X‘。

如果其值为‘1‘,说明是刚才bfs搜索过的节点,它们并未被‘X‘全部包围。则恢复其值为‘O‘。


在leetcode上实际执行时间为20ms.

class Solution {
public:
    void solve(vector<vector<char>>& board) {
        if (board.empty()) return;
        const int row = board.size();
        const int col = board[0].size();
        const char C = '1';
        for (int i=0; i<row; i++) {
            for (int j=0; j<col; j++) {
                if (i && j && i!=row-1 && j!=col-1 || board[i][j]=='X')
                    continue;
            
                queue<pair<int, int> >q;
                q.push(make_pair(i, j));
                board[i][j] = C;
                while (!q.empty()) {
                    int count = q.size();
                    while (count--) {
                        auto xy = q.front();
                        q.pop();
                        if (xy.first && board[xy.first-1][xy.second]=='O') {
                            board[xy.first-1][xy.second] = C;
                            q.push(make_pair(xy.first-1, xy.second));
                        }
                        if (xy.second && board[xy.first][xy.second-1]=='O') {
                            board[xy.first][xy.second-1] = C;
                            q.push(make_pair(xy.first, xy.second-1));
                        }
                        if (xy.first+1<row && board[xy.first+1][xy.second]=='O') {
                            board[xy.first+1][xy.second] = C;
                            q.push(make_pair(xy.first+1, xy.second));
                        }
                        if (xy.second+1<col && board[xy.first][xy.second+1]=='O') {
                            board[xy.first][xy.second+1] = C;
                            q.push(make_pair(xy.first, xy.second+1));
                        }
                    }
                }
            }
        }
        
        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]==C)
                    board[i][j] = 'O';
            }
        }
    }
};


Surrounded Regions -- leetcode

标签:bfs   leetcode   

原文地址:http://blog.csdn.net/elton_xiao/article/details/45950513

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!