1
class Solution {
2
boolean isClosed = true;
3

4
public void solve(char[][] board) {
5
int m = board.length;
6
int n = board[0].length;
7

8
// To identify all those O which are adjacent and unbounded by 'X', we put a temporary value
9
for (int i = 0; i < m; i++) {
10
for (int j = 0; j < n; j++) {
11
if (board[i][j] == 'O' && (i == 0 || j == 0 || i == m - 1 || j == n - 1)) {
12
dfs(board, i, j);
13
}
14
}
15
}
16

17
// revert the temperoray value and also replace remaining O with X
18
for (int i = 0; i < m; i++) {
19
for (int j = 0; j < n; j++) {
20
if (board[i][j] == 'T') board[i][j] = 'O';
21
else if (board[i][j] == 'O') board[i][j] = 'X';
22
}
23
}
24
}
25

26
public void dfs(char[][] board, int i, int j) {
27
if (i < 0 || j < 0 || i >= board.length || j >= board[0].length || board[i][j] != 'O') return;
28

29
board[i][j] = 'T'; // to put a temperory mark/ to mark as visited
30

31
dfs(board, i, j + 1); // Top
32
dfs(board, i, j - 1); // Bottom
33
dfs(board, i + 1, j); // Right
34
dfs(board, i - 1, j); // Left
35
}
36
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0