I just need to find neighbors positions of 2d array using depth first search. for example assume below one is the 2D array.
{{0,0,0,0,0,}, {0,1,1,1,0,}, {0,1,1,1,0,}, {0,1,1,1,0,}, {0,0,0,1,1,},};
print position x and y neighbors positions with value 1 using dfd(x,y) eg: dfd(2,2) so neighbors positions are (1,1),(1,2),(1,3),(2,1),(2,3),(3,1),(3,2),(3,3).
So this is the code I have tried in java
public class Main {
public static void main(String[] args) {
dfs(1,1);
}
static int N = 5;
static int M = 5;
static boolean[][] vis = new boolean[1001][1001];
static int[][] arr ={{0,0,0,0,0,},
{0,1,0,1,0,},
{0,1,1,1,0,},
{0,1,0,0,0,},
{0,0,0,0,0,},};
public static boolean isValid(int x,int y){
if(x<=0 || x>N || y<=0 || y>M){
return false;
}
if(vis[x][y] == true){
return false;
}
return true;
}
static void dfs(int x,int y){
int[] dx = {-1,0,1,0};
int[] dy = {0,1,0,-1};
vis[x][y] = true;
System.out.println("row: "+x+" col: "+y);
for(int i =0;i<4;i++){
if(isValid(x+dx[i],y+dy[i])){
dfs(x+dx[i],y+dy[i]);
}
}
}
}