forked from damaohongtu/JavaInterview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestCycle.java
More file actions
83 lines (74 loc) · 2.11 KB
/
TestCycle.java
File metadata and controls
83 lines (74 loc) · 2.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package CommonProblems.graph;
/**
* @Author MaoTian
* @Classname TestCycle
* @Description 深度优先搜索输出有向图中的所有环
* @Date 下午2:49 2019/9/17
* @Version 1.0
* @Created by mao<[email protected]>
*/
import java.util.ArrayList;
import java.util.Arrays;
public class TestCycle {
private int n;
private int[] visited;//节点状态,值为0的是未访问的
private int[][] e;//有向图的邻接矩阵
private ArrayList<Integer> trace=new ArrayList<Integer>();//从出发节点到当前节点的轨迹
private boolean hasCycle=false;
public TestCycle(int n,int[][] e){
this.n=n;
visited=new int[n];
Arrays.fill(visited,0);
this.e=e;
}
void findCycle(int v) //递归DFS
{
if(visited[v]==1)
{
int j;
//在路径中查找是否有v
if((j=trace.indexOf(v))!=-1)
{
hasCycle=true;
System.out.print("Cycle:");
while(j<trace.size())
{
System.out.print(trace.get(j)+" ");
j++;
}
System.out.print("\n");
return;
}
return;
}
visited[v]=1;
trace.add(v);
for(int i=0;i<n;i++)
{
if(e[v][i]==1){
findCycle(i);
}
}
trace.remove(trace.size()-1);
}
public boolean getHasCycle(){
return hasCycle;
}
public static void main(String[] args) {
int n=7;
int[][] e={
{0,1,1,0,0,0,0},
{0,0,0,1,0,0,0},
{0,0,0,0,0,1,0},
{0,0,0,0,1,0,0},
{0,0,1,0,0,0,0},
{0,0,0,0,1,0,1},
{1,0,1,0,0,0,0}};//有向图的邻接矩阵,值大家任意改.
TestCycle tc=new TestCycle(n,e);
tc.findCycle(0);
//判断是否有环,应该对每一个点进行判断,对于起点的选择!!!
if(!tc.hasCycle){
System.out.println("No Cycle.");
}
}
}