Surrounded Regions

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

Solution: Traverse from the boarder to the inside and mark all the 'O's that are not surrounded by 'X' as 'V' (visited).
1. DFS.
2. BFS (queue).

 1 class Solution {
 2 public:
 3     void solve(vector<vector<char>> &board) {
 4         if (board.empty() || board[0].empty()) return;
 5         int N = board.size(), M = board[0].size();
 6         for (int i = 0; i < N; ++i)
 7             for (int j = 0; j < M; ++j)
 8                 if (i == 0 || j == 0 || i == N-1 || j == M-1)
 9                     dfs(board, i, j); // you may call dfs or bfs here!
10         for (int i = 0; i < N; ++i)
11             for (int j = 0; j < M; ++j)
12                 board[i][j] = (board[i][j] == 'V') ? 'O' : 'X';
13     }
14     
15     // runtime error
16     void dfs(vector<vector<char> > &board, int row, int col) {
17         int N = board.size(), M = board[0].size();
18         if (row < 0 || row >= N || col < 0 || col >= M) return;
19         if (board[row][col] != 'O') return;
20         board[row][col] = 'V';
21         if(row+1 < N && board[row+1][col] == 'O') dfs(board, row+1, col);
22         if(row-1 >= 0 && board[row-1][col] == 'O') dfs(board, row-1, col);
23         if(col+1 < N && board[row][col+1] == 'O') dfs(board, row, col+1);
24         if(col-1 >= 0 && board[row][col-1] == 'O') dfs(board, row, col-1);
25     }
26     
27     void bfs(vector<vector<char> > &board, int row, int col) {
28         if (board[row][col] != 'O') return;
29         int N = board.size(), M = board[0].size();
30         queue<pair<int, int>> q;
31         q.push(make_pair(row, col));
32         while (!q.empty())
33         {
34             int i = q.front().first, j = q.front().second;
35             q.pop();
36             if (i < 0 || i >= N || j < 0 || j >= M) continue;
37             if (board[i][j] != 'O') continue;// important to recheck!
38             board[i][j] = 'V';
39             q.push(make_pair(i-1, j));
40             q.push(make_pair(i+1, j));
41             q.push(make_pair(i, j-1));
42             q.push(make_pair(i, j+1));
43         }
44     }
45 };

 

 

posted @ 2014-04-24 06:17  beehard  阅读(113)  评论(0编辑  收藏  举报