Java- Maze Breadth First Search Shortest Path -
i seem having problem understanding how retrive shortest path discovered breadth first search algorithm implementing. algorithm works can find exit of maze if can reach it. in post mentioned keeping tack of parent after node marked visited. have tried simple implementation of trying keep track of parent including parent point inside point structure when mark path on grid marks paths has traveresed far, believe may have messed keeping track of parent somehow.
any 1 have clue have gone wrong. maybe missing simple? code included below reference.
the maze 2d integer grid. assume 1 wall , 0 movable path.
the point class contains: point parent int x, y; , nothing more.
public point bfs(int x, int y){ queue<point> path = new queue<>(); path.enqueue(new point(x,y));//push current on queue point cur = path.front();//make current point //test code recursive backcall of path cur.setparent(null); //test code recursive backcall of path point end = new point(mwidth-2, mheight-2);//set goal while((!path.isempty())){ point old = cur; cur = path.dequeue(); cur.setparent(old); if(cur.compareto(end)){ return cur;//return point traverse here calling cur.parent path. } else if(maze[cur.getx()][cur.gety()]==1){//enque possible paths maze[cur.getx()][cur.gety()] = 2;//mark visitied if(cur.getx()-1>=0) if(maze[cur.getx()-1][cur.gety()]==1) path.enqueue(new point(cur.getx()-1,cur.gety())); if(cur.getx()+1<mwidth) if(maze[cur.getx()+1][cur.gety()]==1) path.enqueue(new point(cur.getx()+1,cur.gety())); if(cur.gety()-1>=0) if(maze[cur.getx()][cur.gety()-1]==1) path.enqueue(new point(cur.getx(),cur.gety()-1)); if(cur.gety()+1<mheight) if(maze[cur.getx()][cur.gety()+1]==1) path.enqueue(new point(cur.getx(),cur.gety()+1)); } } return null; }
looks oldis no longer parent after multiple iterations. can set parent when adding point queue instead, example:
point next = new point(cur.getx()-1,cur.gety()); next.setparent(cur); path.enqueue(next); then when find end, should able path beginning calling getparent() until it's null.
Comments
Post a Comment