我目前正在尝试编写一个程序来检查是否 directed graph is cyclic or not . 我不确定我做错了什么(我很可能做错了所以所以请StackOverflow,告诉我我的愚蠢!) . 我已经到了不知道可能是什么问题的地步 .
输入是一个邻接列表,例如:
0: 2 4
1: 2 4
2: 3 4
3: 4
4: 0 1 2 3
(0指向2和4; 1指向2和4,依此类推......)
我的想法是检查我正在检查的节点是否为“灰色”(部分探索) . 如果是,则它必须是后边缘,因此是循环图 . 始终探索黑色边缘或交叉边缘,因此不应触发循环消息 . 我的目标是深度搜索
如果A - > B和B - > A,则不应触发有关循环的消息(但A - > B,B - > C,C - > A应该) .
hasCycle调用hasCycleInSubgraph,它通过图的Adjency List递归调用自身 .
class qs {
private ArrayList[] adjList;
private Stack stack;
private ArrayList whiteHat;
private ArrayList greyHat;
private ArrayList blackHat;
public qs(ArrayList[] graph) {
this.adjList = graph;
this.stack = new Stack();
this.whiteHat = new ArrayList();
this.greyHat = new ArrayList();
this.blackHat = new ArrayList();
for (Integer h = 0; h < adjList.length; h++) {
whiteHat.add(h);
}
}
public boolean hasCycle() {
for (Integer i = 0; i < adjList.length; i++) {
// System.out.print("Local root is: ");
// System.out.println(i);
whiteHat.remove(i);
greyHat.add(i);
if (hasCycleInSubgraph(i) == true) {
return true;
}
greyHat.remove(i);
blackHat.add(i);
}
return false;
}
public boolean hasCycleInSubgraph(Integer inp) {
if (blackHat.contains(inp)) {
return false;
}
for (Integer branch : adjList[inp]) {
// System.out.print("Adj is: ");
// System.out.println(branch);
if ( greyHat.contains(branch) && !inp.equals(branch) ) {
return true;
}
whiteHat.remove(branch);
greyHat.add(branch);
if ( hasCycleInSubgraph(branch) == true ) {
return true;
}
greyHat.remove(branch);
blackHat.add(branch);
}
return false;
}
}