我的深度首次搜索完美,但它不涉及週期。我想用DFS打印一個循環。深度首次搜索1個週期打印
printAllPaths(VertexA, VertexC)
會導致這樣的事情:
A B C D C //with cycle since C repeated
A B C
A D C
A D E B C
A E B C
的代碼如下
void printAllPathsUtil(Vertex v, Vertex d, ArrayList<Vertex> path){
v.state = VISITED;
path.add(v);
if (v == d) {
for (Vertex p : path) {
System.out.print("Print: " + p.value + " ");
}
System.out.println();
}
else {
for (Vertex city : v.outboundCity){
if (city.state == UNVISITED) {
printAllPathsUtil(city, d, path);
}
}
}
path.remove(v);
v.state = UNVISITED;
}
void printAllPaths(Vertex v, Vertex u){
clearStates();
ArrayList<Vertex> path = new ArrayList<>();
printAllPathsUtil(v, u, path);
}
頂點類是這樣的:
public class Vertex{
String value;
Vertex previous = null;
int minDistance = Integer.MAX_VALUE;
List<Vertex> inboundCity;
List<Vertex> outboundCity;
State state;
}
我知道我們不應該無限打印的情況。但它應該只打印1個週期。我嘗試了很多東西,但無濟於事。