Depth First Search on 2-D array

杀马特。学长 韩版系。学妹 提交于 2019-12-05 19:05:23

Okay, so there a few issues I see that would prevent your code from working properly so lets look at them one at a time.

First, you dfs function will not iterate through the 'for' loop because it will immediately return. Try changing

dfs(maze, neighbors.get(i));

to

if(dfs(maze, neighbors.get(i))){
    return true;
}

This fixes part of your issue with only searching a single path.

The second issue is with your neighbors. When your dfs does fully explore a path, it should go back a step and check all neighbors. You only have a single top-level neighbors variable, so when your branch terminates with zero neighbors, it thinks all earlier nodes have zero neighbors.

Remove your static neighbors variable

static ArrayList<Point> neighbors = new ArrayList<Point>();

And put a non-static version in getNeighbors

ArrayList<Point> neighbors = new ArrayList<Point>();

This almost completely fixes the search, but for your maze, you will still not find the end.

Your inMaze function is checking bounds incorrectly. You were checking for if x or y was less than length minus one. You only need to use 'less than' for checking the boundary.

if (p.x < maze[0].length && p.x > -1 && p.y < maze.length && p.y > -1)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!