Fixed the path finding algos a bit
This commit is contained in:
parent
0f85e1b4dd
commit
c161e4bdd8
11 changed files with 240 additions and 205 deletions
51
src/zutil/algo/path/DepthFirstSearch.java
Normal file
51
src/zutil/algo/path/DepthFirstSearch.java
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
package zutil.algo.path;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedList;
|
||||
import java.util.Queue;
|
||||
|
||||
/**
|
||||
* A PathFinder class implemented with DFS
|
||||
*
|
||||
* @author Ziver
|
||||
*/
|
||||
public class DepthFirstSearch {
|
||||
private HashSet<PathNode> visited = new HashSet<PathNode>();
|
||||
|
||||
/**
|
||||
* Returns the first path to the destination
|
||||
*
|
||||
* @param start Start Node
|
||||
* @param stop Stop Node
|
||||
* @return A list with the path
|
||||
*/
|
||||
public LinkedList<PathNode> find(PathNode start, PathNode stop){
|
||||
visited.clear();
|
||||
PathNode node = dfs(start, stop);
|
||||
return node.traversTo( start );
|
||||
}
|
||||
|
||||
/**
|
||||
* The DepthFirstSearch algorithm
|
||||
* @param node The node to search from
|
||||
* @return The stop PathNode if a path was found else null
|
||||
*/
|
||||
private PathNode dfs(PathNode node, PathNode stop){
|
||||
visited.add( node );
|
||||
if(node.equals(stop)){
|
||||
return node;
|
||||
}
|
||||
|
||||
for(PathNode next : node.getNeighbors()){
|
||||
if(!visited.contains( next ) && node.getNeighborCost(next) > 0){
|
||||
next.setParentNeighbor(node);
|
||||
PathNode tmp = dfs(next, stop);
|
||||
if(tmp != null){
|
||||
return tmp;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue