Skip to content

Instantly share code, notes, and snippets.

@aaphadke
Last active October 14, 2018 18:19
Show Gist options
  • Save aaphadke/9eb46462280d3724af873ee76dacf8fe to your computer and use it in GitHub Desktop.
Save aaphadke/9eb46462280d3724af873ee76dacf8fe to your computer and use it in GitHub Desktop.
private static int searchMazeBFS() {
int[][] a = {{0,0,0,0},
{0,1,0,0},
{0,1,0,0},
{1,0,1,0}};
Point start = new Point(2,0);
Point end = new Point(2,2);
LinkedList<Point> queue = new LinkedList<Point>();
queue.add(start);
boolean[][] visited= new boolean[a.length][a[0].length];
int[][] distance = new int[a.length][a[0].length];
visited[start.x][start.y] = true;
while(!queue.isEmpty()) {
Point polled = queue.poll();
if(polled.x==end.x && polled.y==end.y) {
return distance[polled.x][polled.y];
}
if(a[polled.x][polled.y]==0) {
System.out.println(polled);
Point neighbourLeft = new Point(polled.x-1,polled.y);
if(isValid(neighbourLeft,visited,a.length,a[0].length)) {
distance[neighbourLeft.x][neighbourLeft.y] = distance[polled.x][polled.y]+1;
queue.add(neighbourLeft);
visited[neighbourLeft.x][neighbourLeft.y] = true;
}
Point neighbourRight = new Point(polled.x+1,polled.y);
if(isValid(neighbourRight,visited,a.length,a[0].length)) {
distance[neighbourRight.x][neighbourRight.y] = distance[polled.x][polled.y]+1;
queue.add(neighbourRight);
visited[neighbourRight.x][neighbourRight.y] = true;
}
Point neighbourTop = new Point(polled.x,polled.y+1);
if(isValid(neighbourTop,visited,a.length,a[0].length)) {
distance[neighbourTop.x][neighbourTop.y] = distance[polled.x][polled.y]+1;
queue.add(neighbourTop);
visited[neighbourTop.x][neighbourTop.y] = true;
}
Point neighbourBottom = new Point(polled.x,polled.y-1);
if(isValid(neighbourBottom,visited,a.length,a[0].length)) {
distance[neighbourBottom.x][neighbourBottom.y] = distance[polled.x][polled.y]+1;
queue.add(neighbourBottom);
visited[neighbourBottom.x][neighbourBottom.y] = true;
}
}
}
return -1;
}
private static boolean isValid(Point p, boolean[][] visited, int rows, int cols) {
if(p.x>=0 && p.y>=0 && p.x<rows && p.y<cols && !visited[p.x][p.y]) {
return true;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment