Scanning the border, if found an 'O', set it to 'Y'. Then do the BFS, get the 'Y' arounded 'O' to Y.

Then the rest of 'O' will be set to the 'X'.

 

 1 class Solution {
 2 public:
 3     void solve(vector<vector<char>> &board) {  
 4            if (board.size() == 0) return;
 5            int n = board.size(), m = board[0].size(), index = 0;
 6            vector<int> xI, yI;
 7            for (int i = 0; i < n; i++) {
 8                if (board[i][0] == 'O') {
 9                    xI.push_back(i);
10                    yI.push_back(0);
11                }
12                if (board[i][m-1] == 'O') {
13                    xI.push_back(i);
14                    yI.push_back(m-1);
15                }
16            }
17            for (int i = 0; i < m; i++) {
18                if (board[0][i] == 'O') {
19                    xI.push_back(0);
20                    yI.push_back(i);
21                }
22                if (board[n-1][i] == 'O') {
23                    xI.push_back(n-1);
24                    yI.push_back(i);
25                }
26            }
27            while (index < xI.size()) {
28                int x = xI[index], y = yI[index++];
29                board[x][y] = 'Y';
30                if (x > 0 && board[x-1][y] == 'O') {xI.push_back(x-1); yI.push_back(y);}
31                if (x < n-1 && board[x+1][y] == 'O') {xI.push_back(x+1); yI.push_back(y);}
32                if (y > 0 && board[x][y-1] == 'O') {xI.push_back(x); yI.push_back(y-1);}
33                if (y < m-1 && board[x][y+1] == 'O') {xI.push_back(x); yI.push_back(y+1);}
34            }
35            for (int i = 0; i < n; i++) {
36                for (int j = 0; j < m; j++) {
37                    if (board[i][j] == 'O') board[i][j] = 'X';
38                    if (board[i][j] == 'Y') board[i][j] = 'O';
39                }
40            }
41     }
42 };

 

posted on 2015-03-24 16:01  keepshuatishuati  阅读(129)  评论(0编辑  收藏  举报