/*
* 给你一个 m x n 的矩阵 board ,由若干字符 'X' 和 'O' ,找到所有被 'X' 围绕的区域,并将这些区域里所有的 'O' 用 'X' 填充。
*
*
* 示例 1:
*
*
* 输入:board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]
* 输出:[["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]
* 解释:被围绕的区间不会存在于边界上,换句话说,任何边界上的 'O' 都不会被填充为 'X'。 任何不在边界上,或不与边界上的 'O' 相连的 'O' 最终都会被填充为 'X'。如果两个元素在水平或垂直方向相邻,则称它们是“相连”的。
* 示例 2:
*
* 输入:board = [["X"]]
* 输出:[["X"]]
*
*
* 提示:
*
* m == board.length
* n == board[i].length
* 1 <= m, n <= 200
* board[i][j] 为 'X' 或 'O'
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/surrounded-regions
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
class Solution {
public:
void solve(vector<vector<char>> &board)
{
row = board.size();
col = board.front().size();
// For edge point, DFS.
for (auto i = 0; i < row; i++) {
for (auto j = 0; j < col; j++) {
if (i == 0 || i == (row - 1) || j == 0 || j == (col - 1)) {
DFS(board, i, j);
}
}
}
for (auto &vec : board) {
for (auto &c : vec) {
if (c == 'O' || c == 'Y') {
c = 'X';
} else if (c == 'P') {
c = 'O';
}
}
}
}
private:
int row{};
int col{};
void DFS(vector<vector<char>> &board, int row, int col)
{
// invalid parameters;
if (!(row >= 0 && row < this->row && col >= 0 && col < this->col)) {
return;
}
// visited. 'Y' means visited 'X', 'P' means visited 'O'.
if (board[row][col] == 'Y' or board[row][col] == 'P') {
return;
}
// 'X'
if (board[row][col] == 'X') {
board[row][col] = 'Y';
return;
}
// 'O'
board[row][col] = 'P';
static vector<pair<int, int>> direct{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
for (const auto &item : direct) {
DFS(board, row + item.first, col + item.second);
}
}
};