java list 有向图_Java检测循环有向图
我目前正在嘗試編寫一個程序來檢查是否 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;
}
}
總結
以上是生活随笔為你收集整理的java list 有向图_Java检测循环有向图的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 关于计算机的英语演讲稿三分钟,以计算机为
- 下一篇: java+arrayblockquene