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;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值