Tuesday, June 14, 2016

Surrounded Regions -- LintCode

[Question]
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.
Example
X X X X
X O O X
X X O X
X O X X
After capture all regions surrounded by 'X', the board should be:
X X X X
X X X X
X X X X
X O X X

[Analysis]
Based on the given example, the 'O's on boundaries of board are not considered as surrounded elements. Therefore, rule out all 'O's on the boundaries and all 'O's adjacent to those, the rest of 'O's will be turned into 'X' -- using BFS.


[Solution]
class Solution {
public:
    /**
     * @param board a 2D board containing 'X' and 'O'
     * @return void
     */
    void markNeighbours(pair<int, int> & pos, queue<pair<int,int>> & que, vector<vector<char>>& b) {
        int x = pos.first; int y = pos.second;

        if (y-1>=0 && b[x][y-1]=='O') {b[x][y-1] = 'A'; que.push({x,y-1}); }
        if (x-1>=0 && b[x-1][y]=='O') {b[x-1][y] = 'A'; que.push({x-1,y}); }
        if (y+1<b[0].size() && b[x][y+1]=='O') {b[x][y+1]='A'; que.push({x,y+1});}
        if (x+1<b.size() && b[x+1][y]=='O') {b[x+1][y]='A'; que.push({x+1,y}); }
       
    }
    void surroundedRegions(vector<vector<char>>& board) {
        if (board.empty()) return;
        // Write your code here
        queue<pair<int,int>> que;
       
        int w = board[0].size();
        int h = board.size();
       
        for (int i=0; i<h; i++) {
            if (board[i][0] == 'O') {
                board[i][0] ='A';
                que.push({i,0});
            }
            if (board[i][w-1] == 'O') {
                board[i][w-1] = 'A';
                que.push({i,w-1});
            }
        }
       
        for (int j=1; j<w-1; j++) {
            if (board[0][j] == 'O') {
                board[0][j] = 'A';
                que.push({0,j});
            }
            if (board[h-1][j] == 'O') {
                board[h-1][j] = 'A';
                que.push({h-1,j});
            }
        }
       
        while (!que.empty()) {
            auto p = que.front();
            que.pop();
            markNeighbours(p, que, board);
        }
       
        for (auto& line: board)
            for (auto& c: line)
                if (c=='A') c= 'O';
                else if (c=='O') c='X';
    }
};

No comments:

Post a Comment