You are viewing a single comment's thread. Return to all comments →
Simple Java Solution
public static int maxRegion(List<List<Integer>> grid) { // Write your code here int max=0; int visited[][]=new int[grid.size()][grid.get(0).size()]; for(int i=0;i<grid.size();i++) { for(int j=0;j<grid.get(0).size();j++) { if(grid.get(i).get(j)==1 && visited[i][j]==0) { visited[i][j]=1; int count=0; Queue<String> q=new LinkedList<String>(); q.add(Integer.toString(i)+" "+Integer.toString(j)); while(q.size()>0) { String str[]=q.poll().split(" "); count++; int x=Integer.parseInt(str[0]); int y=Integer.parseInt(str[1]); if(x-1>=0 && grid.get(x-1).get(y)==1 && visited[x-1][y]==0) { visited[x-1][y]=1; q.add(Integer.toString(x-1)+" "+Integer.toString(y)); } if(y-1>=0 && grid.get(x).get(y-1)==1 && visited[x][y-1]==0) { visited[x][y-1]=1; q.add(Integer.toString(x)+" "+Integer.toString(y-1)); } if(x+1<grid.size() && grid.get(x+1).get(y)==1 && visited[x+1][y]==0) { visited[x+1][y]=1; q.add(Integer.toString(x+1)+" "+Integer.toString(y)); } if(y+1<grid.get(0).size() && grid.get(x).get(y+1)==1 && visited[x][y+1]==0) { visited[x][y+1]=1; q.add(Integer.toString(x)+" "+Integer.toString(y+1)); } if(x-1>=0 && y-1>=0 && grid.get(x-1).get(y-1)==1 && visited[x-1][y-1]==0) { visited[x-1][y-1]=1; q.add(Integer.toString(x-1)+" "+Integer.toString(y-1)); } if(x-1>=0 && y+1<grid.get(0).size() && grid.get(x-1).get(y+1)==1 && visited[x-1][y+1]==0) { visited[x-1][y+1]=1; q.add(Integer.toString(x-1)+" "+Integer.toString(y+1)); } if(x+1<grid.size() && y+1<grid.get(0).size() && grid.get(x+1).get(y+1)==1 && visited[x+1][y+1]==0) { visited[x+1][y+1]=1; q.add(Integer.toString(x+1)+" "+Integer.toString(y+1)); } if(x+1<grid.size() && y-1>=0 && grid.get(x+1).get(y-1)==1 && visited[x+1][y-1]==0) { visited[x+1][y-1]=1; q.add(Integer.toString(x+1)+" "+Integer.toString(y-1)); } } if(count>max) { max=count; } } } } return max; }
Seems like cookies are disabled on this browser, please enable them to open this website
DFS: Connected Cell in a Grid
You are viewing a single comment's thread. Return to all comments →
Simple Java Solution