130. Surrounded Regions
/*
* @lc app=leetcode id=130 lang=cpp
*
* [130] Surrounded Regions
*
* https://leetcode.com/problems/surrounded-regions/description/
*
* algorithms
* Medium (41.16%)
* Likes: 9078
* Dislikes: 2037
* Total Accepted: 893.7K
* Total Submissions: 2.1M
* Testcase Example: '[["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]'
*
* You are given an m x n matrix board containing letters 'X' and 'O', capture
* regions that are surrounded:
*
*
* Connect: A cell is connected to adjacent cells horizontally or
* vertically.
* Region: To form a region connect every 'O' cell.
* Surround: The region is surrounded with 'X' cells if you can connect the
* region with 'X' cells and none of the region cells are on the edge of the
* board.
*
*
* To capture a surrounded region, replace all 'O's with 'X's in-place within
* the original board. You do not need to return anything.
*
*
* Example 1:
*
*
* Input: board =
* [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]
*
* Output:
* [["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]
*
* Explanation:
*
* In the above diagram, the bottom region is not captured because it is on the
* edge of the board and cannot be surrounded.
*
*
* Example 2:
*
*
* Input: board = [["X"]]
*
* Output: [["X"]]
*
*
*
* Constraints:
*
*
* m == board.length
* n == board[i].length
* 1 <= m, n <= 200
* board[i][j] is 'X' or 'O'.
*
*
*/
// @lc code=start
class Solution {
public:
void solve(vector<vector<char>>& board)
{
int rows = board.size(), cols = board[0].size();
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
if (board[i][j] == 'O' && (i == 0 || j == 0 || i == rows - 1 || j == cols - 1))
{
dfs(board, i, j);
}
}
}
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
if (board[i][j] == 'O') board[i][j] = 'X';
if (board[i][j] == '#') board[i][j] = 'O';
}
}
}
void dfs(vector<vector<char>>& board, int i, int j)
{
int rows = board.size(), cols = board[0].size();
if (i < 0 || j < 0 || i >= rows || j >= cols || board[i][j] != 'O')
{
return;
}
board[i][j] = '#';
vector<vector<int>> directions = {{0, -1}, {0, 1}, {1, 0}, {-1, 0}};
for(auto dir : directions)
{
dfs(board, i + dir[0], j + dir[1]);
}
}
};
// @lc code=end
- T:
- S: