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',找到一个之后做一个DFS或者BFS均可,做的时候随时检查是否到达棋盘的边缘。到的话就不转化成‘X',否则按照搜索记录把棋盘上的网格转换成’X'。
题解:
class Solution { public: void navigate_and_fill (vector<vector<char>>& board, int R, int C, int M, int N) { vector<pair<int, int>> nav_history; bool surrounded = true; queue<pair<int, int>> nav_queue; nav_queue.push (make_pair (R, C)); board[R][C] = 'o'; while (!nav_queue.empty()) { auto q = nav_queue.front(); nav_history.push_back(q); nav_queue.pop(); if (q.first == 0 || q.first == M - 1 || q.second == 0 || q.second == N - 1) surrounded = false; if (q.first != 0 && board[q.first - 1][q.second] == 'O') { board[q.first - 1][q.second] = 'o'; nav_queue.push (make_pair (q.first - 1, q.second)); } if (q.first != M - 1 && board[q.first + 1][q.second] == 'O') { board[q.first + 1][q.second] = 'o'; nav_queue.push (make_pair (q.first + 1, q.second)); } if (q.second != 0 && board[q.first][q.second - 1] == 'O') { board[q.first][q.second - 1] = 'o'; nav_queue.push (make_pair (q.first, q.second - 1)); } if (q.second != N - 1 && board[q.first][q.second + 1] == 'O') { board[q.first][q.second + 1] = 'o'; nav_queue.push (make_pair (q.first , q.second + 1)); } } if (surrounded) for (auto & n : nav_history) board[n.first][n.second] = 'X'; } void solve (vector<vector<char>>& board) { const int M = board.size(); if (M == 0) return; const int N = board[0].size(); if (N == 0) return; for (int R = 0; R < M; ++R) for (int C = 0; C < N; ++C) if (board[R][C] == 'O') navigate_and_fill (board, R, C, M, N); for (auto & r : board) for (auto & c : r) if (c == 'o') c = 'O'; } };