題目:
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,則表示有出路,這時,以找到的O點為起點,採用BFS或DFS進行遍歷,找到與其他與該O點相鄰的O點,然後將其置為*,第一步處理完後,再重新遍歷整個矩陣,將為*的點置為O,為O的點置為X即可。
實現程式碼:
#include <iostream> #include <vector> #include <queue> using namespace std; /* 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 */ class Solution { public: void solve(vector<vector<char>> &board) { if(board.empty() || board[0].empty()) return ; int rows = board.size(); int cols = board[0].size(); for(int i = 0; i < rows; i++) { if(board[i][0] == 'O') bfs(i, 0, board, rows, cols); if(board[i][cols-1] == 'O') bfs(i, cols-1, board, rows, cols); } for(int j = 0; j < cols; j++) { if(board[0][j] == 'O') bfs(0, j, board, rows, cols); if(board[rows-1][j] == 'O') bfs(rows-1, j, board, rows, cols); } for(int i = 0; i < rows; i++) for(int j = 0; j < cols; j++) if(board[i][j] == 'O') board[i][j] = 'X'; else if(board[i][j] == '*') board[i][j] = 'O'; } void bfs(int i, int j, vector<vector<char>> &board, int rows, int cols) { queue<pair<int, int>> qu; qu.push(make_pair(i, j)); while(!qu.empty()) { pair<int, int> p = qu.front(); qu.pop(); int ii = p.first; int jj = p.second; if(ii < 0 || ii >= rows || jj < 0 || jj >= cols || board[ii][jj] != 'O') continue; board[ii][jj] = '*'; qu.push(make_pair(ii, jj-1)); qu.push(make_pair(ii, jj+1)); qu.push(make_pair(ii-1, jj)); qu.push(make_pair(ii+1, jj)); } } }; int main(void) { return 0; }