surrounded regions

This commit is contained in:
Evan Ferrao 2026-02-14 19:41:40 +05:30 committed by GitHub
parent ef83c1be47
commit fdb2d87fb1
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -0,0 +1,141 @@
// https://leetcode.com/problems/surrounded-regions/
import java.util.*;
import java.io.*;
class Main {
static class Node{
int row;
int col;
Node(int row, int col){
this.row = row;
this.col = col;
}
}
// DFS
public static void dfs(Node node, char board[][], boolean doNotTouch[][]){
int m = board.length;
int n = board[0].length;
int r = node.row;
int c = node.col;
doNotTouch[r][c] = true;
int dr[] = {-1, 0, 1, 0};
int dc[] = {0, 1, 0, -1};
for(int k=0;k<4;k++){
int nr = r + dr[k];
int nc = c + dc[k];
if(nr>=0 && nc>=0 && nr<m && nc<n &&
!doNotTouch[nr][nc] && board[nr][nc]=='O'){
dfs(new Node(nr, nc), board, doNotTouch);
}
}
}
// BFS
public static void bfs(Node start, char board[][], boolean doNotTouch[][]){
int m = board.length;
int n = board[0].length;
Queue<Node> q = new LinkedList<>();
q.add(start);
doNotTouch[start.row][start.col] = true;
int dr[] = {-1, 0, 1, 0};
int dc[] = {0, 1, 0, -1};
while(!q.isEmpty()){
Node cur = q.poll();
for(int k=0;k<4;k++){
int nr = cur.row + dr[k];
int nc = cur.col + dc[k];
if(nr>=0 && nc>=0 && nr<m && nc<n &&
!doNotTouch[nr][nc] && board[nr][nc]=='O'){
doNotTouch[nr][nc] = true;
q.add(new Node(nr, nc));
}
}
}
}
public static void solve(char board[][]){
int m = board.length;
int n = board[0].length;
boolean doNotTouch[][] = new boolean[m][n];
// borders
for(int i=0;i<m;i++){
if(board[i][0]=='O'){
dfs(new Node(i,0), board, doNotTouch);
// bfs(new Node(i,0), board, doNotTouch);
}
if(board[i][n-1]=='O'){
dfs(new Node(i,n-1), board, doNotTouch);
// bfs(new Node(i,n-1), board, doNotTouch);
}
}
for(int j=0;j<n;j++){
if(board[0][j]=='O'){
dfs(new Node(0,j), board, doNotTouch);
// bfs(new Node(0,j), board, doNotTouch);
}
if(board[m-1][j]=='O'){
dfs(new Node(m-1,j), board, doNotTouch);
// bfs(new Node(m-1,j), board, doNotTouch);
}
}
char finalAns[][] = new char[m][n];
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(doNotTouch[i][j]) finalAns[i][j] = board[i][j];
else finalAns[i][j] = 'X';
}
}
// copy back
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
board[i][j] = finalAns[i][j];
}
}
}
// DRIVER
public static void main(String args[]){
char board[][] = {
{'X','X','X','X'},
{'X','O','O','X'},
{'X','X','O','X'},
{'X','O','X','X'}
};
solve(board);
for(int i=0;i<board.length;i++){
for(int j=0;j<board[0].length;j++){
System.out.printf("%c ", board[i][j]);
}
System.out.printf("\n");
}
}
}