Surrounded Regions
Surrounded Regions is a medium graphs problem solved with the dfs - complement trick pattern.
The best approach, optimal (dfs from the border, the complement trick), runs in O(m · n) time and O(m · n) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from check each region separately up.
Problem
In a board of 'X' and 'O', capture every region of O that is completely surrounded by X by flipping it to X. A region connected to the border is not surrounded and stays.
Examples
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]]- Why
- The bottom O touches the border, so it survives.
Example 2
- Input
board = [[O]]- Output
[[O]]
Constraints
1 <= m, n <= 200; cells are 'X' or 'O'.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (2 examples, or your own). Submit also runs 9 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Check each region separately | O(m · n) | O(m · n) |
| Optimal (DFS from the border, the complement trick) | O(m · n) | O(m · n) |
1Check each region separately
O(m · n)O(m · n)For each unvisited O, BFS its whole region, noting whether it touches the border. If not, flip the region.
- BFS the region, collecting cells and a touchesBorder flag.
- If !touchesBorder, flip every collected cell to X.
class Solution {
public void solve(char[][] board) {
int m = board.length, n = board[0].length;
boolean[][] seen = new boolean[m][n];
int[][] dirs = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++) {
if (board[i][j] != 'O' || seen[i][j]) continue;
List<int[]> region = new ArrayList<>();
boolean border = false;
Queue<int[]> q = new ArrayDeque<>();
q.add(new int[] { i, j });
seen[i][j] = true;
while (!q.isEmpty()) {
int[] c = q.poll();
region.add(c);
if (c[0] == 0 || c[1] == 0 || c[0] == m - 1 || c[1] == n - 1) border = true;
for (int[] d : dirs) {
int r = c[0] + d[0], k = c[1] + d[1];
if (r >= 0 && k >= 0 && r < m && k < n && board[r][k] == 'O' && !seen[r][k]) {
seen[r][k] = true;
q.add(new int[] { r, k });
}
}
}
if (!border) for (int[] c : region) board[c[0]][c[1]] = 'X';
}
}
}class Solution:
def solve(self, board: List[List[str]]) -> None:
m, n = len(board), len(board[0])
seen = [[False] * n for _ in range(m)]
dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
for i in range(m):
for j in range(n):
if board[i][j] != 'O' or seen[i][j]:
continue
region = []
border = False
q = deque([(i, j)])
seen[i][j] = True
while q:
c = q.popleft()
region.append(c)
if c[0] == 0 or c[1] == 0 or c[0] == m - 1 or c[1] == n - 1:
border = True
for d in dirs:
r, k = c[0] + d[0], c[1] + d[1]
if r >= 0 and k >= 0 and r < m and k < n and board[r][k] == 'O' and not seen[r][k]:
seen[r][k] = True
q.append((r, k))
if not border:
for c in region:
board[c[0]][c[1]] = 'X'class Solution {
public:
void solve(vector<vector<char>>& board) {
int m = board.size(), n = board[0].size();
vector<vector<bool>> seen(m, vector<bool>(n, false));
int dirs[4][2] = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++) {
if (board[i][j] != 'O' || seen[i][j]) continue;
vector<pair<int, int>> region;
bool border = false;
queue<pair<int, int>> q;
q.push({i, j});
seen[i][j] = true;
while (!q.empty()) {
auto c = q.front();
q.pop();
region.push_back(c);
if (c.first == 0 || c.second == 0 || c.first == m - 1 || c.second == n - 1) border = true;
for (auto& d : dirs) {
int r = c.first + d[0], k = c.second + d[1];
if (r >= 0 && k >= 0 && r < m && k < n && board[r][k] == 'O' && !seen[r][k]) {
seen[r][k] = true;
q.push({r, k});
}
}
}
if (!border) for (auto& c : region) board[c.first][c.second] = 'X';
}
}
};function solve(board) {
const m = board.length, n = board[0].length;
const seen = Array.from({ length: m }, () => new Array(n).fill(false));
const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]];
for (let i = 0; i < m; i++)
for (let j = 0; j < n; j++) {
if (board[i][j] !== 'O' || seen[i][j]) continue;
const region = [];
let border = false;
const q = [[i, j]];
let head = 0;
seen[i][j] = true;
while (head < q.length) {
const c = q[head++];
region.push(c);
if (c[0] === 0 || c[1] === 0 || c[0] === m - 1 || c[1] === n - 1) border = true;
for (const d of dirs) {
const r = c[0] + d[0], k = c[1] + d[1];
if (r >= 0 && k >= 0 && r < m && k < n && board[r][k] === 'O' && !seen[r][k]) {
seen[r][k] = true;
q.push([r, k]);
}
}
}
if (!border) for (const c of region) board[c[0]][c[1]] = 'X';
}
}2Optimal (DFS from the border, the complement trick)
O(m · n)O(m · n)Recursion depth in the worst case.Start a DFS from every border O and mark everything it reaches as safe ('#'). Then scan: remaining O cells are surrounded and become X, and '#' cells turn back into O.
- For each border cell that is O, mark(r, c) → '#'.
- Scan all cells: O → X, # → O.
class Solution {
public void solve(char[][] board) {
int m = board.length, n = board[0].length;
for (int i = 0; i < m; i++) { mark(board, i, 0); mark(board, i, n - 1); }
for (int j = 0; j < n; j++) { mark(board, 0, j); mark(board, m - 1, j); }
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
board[i][j] = board[i][j] == '#' ? 'O' : 'X';
}
private void mark(char[][] b, int r, int c) {
if (r < 0 || c < 0 || r >= b.length || c >= b[0].length || b[r][c] != 'O') return;
b[r][c] = '#';
mark(b, r + 1, c);
mark(b, r - 1, c);
mark(b, r, c + 1);
mark(b, r, c - 1);
}
}class Solution:
def solve(self, board: List[List[str]]) -> None:
m, n = len(board), len(board[0])
for i in range(m):
self.mark(board, i, 0)
self.mark(board, i, n - 1)
for j in range(n):
self.mark(board, 0, j)
self.mark(board, m - 1, j)
for i in range(m):
for j in range(n):
board[i][j] = 'O' if board[i][j] == '#' else 'X'
def mark(self, b: List[List[str]], r: int, c: int) -> None:
if r < 0 or c < 0 or r >= len(b) or c >= len(b[0]) or b[r][c] != 'O':
return
b[r][c] = '#'
self.mark(b, r + 1, c)
self.mark(b, r - 1, c)
self.mark(b, r, c + 1)
self.mark(b, r, c - 1)class Solution {
public:
void solve(vector<vector<char>>& board) {
int m = board.size(), n = board[0].size();
for (int i = 0; i < m; i++) { mark(board, i, 0); mark(board, i, n - 1); }
for (int j = 0; j < n; j++) { mark(board, 0, j); mark(board, m - 1, j); }
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
board[i][j] = board[i][j] == '#' ? 'O' : 'X';
}
private:
void mark(vector<vector<char>>& b, int r, int c) {
if (r < 0 || c < 0 || r >= (int)b.size() || c >= (int)b[0].size() || b[r][c] != 'O') return;
b[r][c] = '#';
mark(b, r + 1, c);
mark(b, r - 1, c);
mark(b, r, c + 1);
mark(b, r, c - 1);
}
};function solve(board) {
const m = board.length, n = board[0].length;
for (let i = 0; i < m; i++) { mark(board, i, 0); mark(board, i, n - 1); }
for (let j = 0; j < n; j++) { mark(board, 0, j); mark(board, m - 1, j); }
for (let i = 0; i < m; i++)
for (let j = 0; j < n; j++)
board[i][j] = board[i][j] === '#' ? 'O' : 'X';
}
function mark(b, r, c) {
if (r < 0 || c < 0 || r >= b.length || c >= b[0].length || b[r][c] !== 'O') return;
b[r][c] = '#';
mark(b, r + 1, c);
mark(b, r - 1, c);
mark(b, r, c + 1);
mark(b, r, c - 1);
}Edge cases to test
- Every O connected to the border
- Single row or column
Hints
Hint 1
It is hard to prove a region is surrounded, but easy to find regions that are not: they touch the border. Mark those, then flip everything else (the complement).
FAQ
What is the best time complexity for Surrounded Regions?
Optimal (DFS from the border, the complement trick) runs in O(m · n) time and O(m · n) extra space.
Which pattern does Surrounded Regions use?
It is a graphs problem that uses the dfs - complement trick pattern.
Is there a brute force solution for Surrounded Regions?
Yes. Check each region separately takes O(m · n) time and O(m · n) space. For each unvisited O, BFS its whole region, noting whether it touches the border.
Which edge cases should I test for Surrounded Regions?
Every O connected to the border; Single row or column.