Leetcode•Sep 22, 2025
Surrounded Regions
Hazrat Ali
Leetcode
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 theboard.
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"]]
Solution
const dx = [-1, 1, 0, 0];
const dy = [0, 0, -1, 1];
/**
* @param {character[][]} board
* @return {void}
*/
const solve = board => {
if (!board || board.length === 0 || board[0].length === 0) return;
const n = board.length;
const m = board[0].length;
for (let i = 0; i < n; i++) {
for (let j = 0; j < m; j++) {
if ((i === 0 || i === n - 1 || j === 0 || j === m - 1) && board[i][j] === 'O') {
bfs(board, n, m, i, j);
}
}
}
for (let i = 1; i < n; i++) {
for (let j = 1; j < m; j++) {
if (board[i][j] === 'O') {
board[i][j] = 'X';
}
}
}
for (let i = 0; i < n; i++) {
for (let j = 0; j < m; j++) {
if (board[i][j] === '1') {
board[i][j] = 'O';
}
}
}
};
const bfs = (board, n, m, i, j) => {
const queue = [];
queue.push([i, j]);
board[i][j] = '1';
while (queue.length > 0) {
const pos = queue.shift();
for (let k = 0; k < 4; k++) {
i = pos[0] + dx[k];
j = pos[1] + dy[k];
if (i >= 0 && i < n && j >= 0 && j < m && board[i][j] === 'O') {
board[i][j] = '1';
queue.push([i, j]);
}
}
}
};