目前我尝试了解有关java的更多信息并尝试编写图表代码。 我有一个HashMap。目前我想实施DFS,但它不会起作用。
我想将从startNode可以实现的所有节点添加到List
原则上代码是正确的还是正确的?如果我测试我的程序,我会得到一个NullPointerException。但我不知道为什么。我知道一个NPE,但在我看来,我的代码不应该抛出NPE。因此,请不要将其标记为NullPointer问题的副本。
非常感谢您的帮助!
这是我的代码:
/**
* For a given node the method returns all nodes the outgoing edges of the node directly lead to.
*
* @return list containing all directly connected nodes.
*/
@Override
public List<Node> getAdjacentNodes(Node startnode) {
List<Node> nodes = null;
if (startnode != null && this.nodes.values().contains(startnode)) {
return startnode.getAdjacentNodes();
}
nodes = new LinkedList<Node>();
return nodes;
}
@Override
public List<Node> getAdjacentNodes(int startnode) {
return getAdjacentNodes(nodes.get(startnode));
}public List<Node> depthFirstSearch(Node startNode){
LinkedList<Node> nodeList = null;
resetState();
//Get a List with all Adjacent Nodes from the startNode
List<Node> node = getAdjacentNodes(startNode);
//Test for each of the ADjacent Nodes from startNode if the current status is white
for(Node child : node) {
//Is the status white, run the recursive method
if(child.status == Node.WHITE) {
runDFS(child);
}
}
return nodeList;
}
public LinkedList<Node> runDFS(Node child) {
//Create a LinkedList as in the depthFirstSearch-Method
LinkedList<Node> nodeList = null;
//Set the status from the current child to GRAY
child.status = Node.GRAY;
//For each Child from the AdjacentsNodes from the child check if color is white
for(Node nextNode : getAdjacentNodes(child)) {
if (hasWhiteNeighbor(nextNode) == true) {
//is color white execute the runDFS method again to get to the last node
runDFS(nextNode);
}
//If the color is not white set it to black and add the node to List, because last node was found
else {
child.status = Node.BLACK;
nodeList.add(child);
}
}
return nodeList;
}