⬅ Previous Topic
Distance of Nearest Cell Having 1 - Grid BFSNext Topic ⮕
Number of Enclaves in Grid⬅ Previous Topic
Distance of Nearest Cell Having 1 - Grid BFSNext Topic ⮕
Number of Enclaves in GridTopic Contents
Given a 2D matrix of size N x M
filled with characters 'O'
and 'X'
, the goal is to replace all 'O'
cells that are completely surrounded by 'X'
on all four sides (up, down, left, right).
'O's that are on the border or connected to a border 'O'
should not be changed. Only 'O'
s that are fully enclosed by 'X'
must be replaced.
'O'
is found on the border, start a DFS/BFS from there to mark all connected 'O's as '#'
.'O'
, change it to 'X'
.'#'
, revert it to 'O'
.function solve(board) {
const rows = board.length;
if (rows === 0) return;
const cols = board[0].length;
function dfs(r, c) {
if (r < 0 || c < 0 || r >= rows || c >= cols || board[r][c] !== 'O') return;
board[r][c] = '#';
dfs(r + 1, c);
dfs(r - 1, c);
dfs(r, c + 1);
dfs(r, c - 1);
}
for (let i = 0; i < rows; i++) {
if (board[i][0] === 'O') dfs(i, 0);
if (board[i][cols - 1] === 'O') dfs(i, cols - 1);
}
for (let j = 0; j < cols; j++) {
if (board[0][j] === 'O') dfs(0, j);
if (board[rows - 1][j] === 'O') dfs(rows - 1, j);
}
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
if (board[i][j] === 'O') board[i][j] = 'X';
if (board[i][j] === '#') board[i][j] = 'O';
}
}
return board;
}
const board = [
["X", "X", "X", "X"],
["X", "O", "O", "X"],
["X", "X", "O", "X"],
["X", "O", "X", "X"]
];
console.log("Updated Board:", solve(board));
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(m × n) | Even if there are no 'O's in the matrix, the algorithm must check every border element and traverse the matrix once. |
Average Case | O(m × n) | Each cell is visited once during border traversal and once during the final transformation, resulting in linear complexity based on the number of cells. |
Worst Case | O(m × n) | If the entire matrix is filled with 'O's, DFS/BFS could touch each element multiple times, but the total work remains bounded by O(m × n). |
O(m × n)
Explanation: In the worst case, a DFS/BFS queue or recursion stack can hold all cells in the matrix when marking connected regions.
⬅ Previous Topic
Distance of Nearest Cell Having 1 - Grid BFSNext Topic ⮕
Number of Enclaves in GridYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.