My solution by firstly searching the boundary ones


  • 0
    S

    This is my code. I start searching from the boundary and mark 'O's as 'C'. Then the second traverse make the 'O' to 'X' and 'C' to 'O'.

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

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.