
Sponsored
Sponsored
This approach uses Depth-First Search (DFS) to mark all 'O's connected to the boundary as safe. These 'O's cannot be converted to 'X' because they are on the boundary or connected to the boundary. The rest of the 'O's can be safely converted to 'X'.
Time Complexity: O(m * n), Space Complexity: O(m * n) due to the DFS recursion stack.
1var solve = function(board) {
2 function dfs(row, col) {
3 if (row < 0 || col < 0 || row >= m || col >= n || board[row][col] !== 'O') return;
4 board[row][col] = 'A';
5 dfs(row - 1, col);
6 dfs(row + 1, col);
7 dfs(row, col - 1);
8 dfs(row, col + 1);
9 }
10
11 let m = board.length;
12 if (m === 0) return;
13 let n = board[0].length;
14
15 for (let i = 0; i < m; i++) {
16 if (board[i][0] === 'O') dfs(i, 0);
17 if (board[i][n - 1] === 'O') dfs(i, n - 1);
18 }
19
20 for (let j = 0; j < n; j++) {
21 if (board[0][j] === 'O') dfs(0, j);
22 if (board[m - 1][j] === 'O') dfs(m - 1, j);
23 }
24
25 for (let i = 0; i < m; i++) {
26 for (let j = 0; j < n; j++) {
27 if (board[i][j] === 'O') board[i][j] = 'X';
28 if (board[i][j] === 'A') board[i][j] = 'O';
29 }
30 }
31};JavaScript code defines a dfs function to handle each region, converting safe 'O's to 'A's. It then performs conversion of remaining 'O's to 'X'.
This approach uses Breadth-First Search (BFS) utilizing a queue to explore 'O's connected to the boundary. This approach is iterative and avoids deep recursion, keeping the method stack usage low.
Time Complexity: O(m * n), Space Complexity: O(m * n) for the queue's maximal use.
1using System;
2using System.Collections.Generic;
public class Solution {
private void Bfs(char[][] board, int row, int col, int m, int n) {
Queue<(int, int)> q = new Queue<(int, int)>();
q.Enqueue((row, col));
board[row][col] = 'A';
while (q.Count > 0) {
var (curRow, curCol) = q.Dequeue();
int[][] directions = new int[][] {
new int[] {1, 0},
new int[] {-1, 0},
new int[] {0, 1},
new int[] {0, -1}
};
foreach (var dir in directions) {
int newRow = curRow + dir[0];
int newCol = curCol + dir[1];
if (newRow >= 0 && newRow < m && newCol >= 0 && newCol < n && board[newRow][newCol] == 'O') {
board[newRow][newCol] = 'A';
q.Enqueue((newRow, newCol));
}
}
}
}
public void Solve(char[][] board) {
int m = board.Length;
if (m == 0) return;
int n = board[0].Length;
for (int i = 0; i < m; i++) {
if (board[i][0] == 'O') Bfs(board, i, 0, m, n);
if (board[i][n - 1] == 'O') Bfs(board, i, n - 1, m, n);
}
for (int j = 0; j < n; j++) {
if (board[0][j] == 'O') Bfs(board, 0, j, m, n);
if (board[m - 1][j] == 'O') Bfs(board, m - 1, j, m, n);
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == 'O') board[i][j] = 'X';
if (board[i][j] == 'A') board[i][j] = 'O';
}
}
}
}C# application of BFS leverages a queue extensively, managing mutable states and directional processing thoroughly across nodes at each array index explored.