Skip to main content

130. Surrounded Regions

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';
}
}
}

# a dfs function designed to mark boundary grids with '#' characters
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]);
}
};
  • T: O()O()
  • S: O()O()