-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathSurrounded Regions.java
38 lines (31 loc) · 1.2 KB
/
Surrounded Regions.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// Runtime: 3 ms (Top 54.99%) | Memory: 51.8 MB (Top 39.25%)
class Solution {
boolean isClosed = true;
public void solve(char[][] board) {
int m = board.length;
int n = board[0].length;
// To identify all those O which are adjacent and unbounded by 'X', we put a temporary value
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(board[i][j] == 'O' && (i == 0 || j == 0 || i == m-1 || j == n-1) ){
dfs(board, i, j);
}
}
}
// revert the temperoray value and also replace remaining O with X
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(board[i][j] == 'T') board[i][j] = 'O';
else if(board[i][j] == 'O') board[i][j] = 'X';
}
}
}
public void dfs(char[][] board, int i, int j){
if(i<0 || j<0 || i>= board.length || j>=board[0].length || board[i][j] != 'O') return;
board[i][j] = 'T'; // to put a temperory mark/ to mark as visited
dfs(board, i, j+1); // Top
dfs(board, i, j-1); // Bottom
dfs(board, i+1, j); // Right
dfs(board, i-1, j); // Left
}
}