我尝试使用DFS解决此问题。我的代码如下:
public static void main(String[] args){
// building a graph g. g has a method getNodes() that can return all the nodes in the graph.
// ...
for(GraphNode n : g.getNodes())
n.state = State.Unvistied;
node1.state = State.Visiting;
isRoute(g, node1, node2);
}
public boolean isRoute(Graph g, GraphNode start, GraphNode end){
for(GraphNode gn : start.getAdjacent()){
if(gn.state != State.Visited){
if(gn == end)
return true;
else {
gn.state = State.Visiting;
if(isRoute(g, gn, end))
return true;
}
}
}
start.state = State.Visited;
return false;
}
class GraphNode {
private GraphNode adjacent[];
private String vertex;
public State state;
public GraphNode(String vertex, int adjacentLength) {
this.vertex = vertex;
adjacent = new GraphNode[adjacentLength];
}
public GraphNode[] getAdjacent() {
return adjacent;
}
public String getVertex() {
return vertex;
}
}
public enum State {
Unvistied, Visited, Visiting;
}
我试图用一个示例图表在纸上运行这个算法,看起来是正确的。 然而,我不知道如何确定,即证明这个算法,特别是当它是递归的并且不容易运行测试用例时,如图中所示,是正确的。你们可以吗?给我一些见解?谢谢!