깊이 우선 검색 출력 은 그림 에 있 는 모든 링(JAVA)이 있 습 니 다.

2304 단어 그림.
그림:그림 에 있 는 모든 고 리 를 구하 세 요.
[img]http://dl.iteye.com/upload/attachment/0076/2311/5f987942-21b0-33b0-b0df-e9b62b9d7c65.gif[/img]
import java.util.ArrayList;
import java.util.Arrays;
public class TestCycle {
private int n;
private int[] visited;// , 0
private int[][] e;//
private ArrayList trace=new ArrayList();//
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;
if((j=trace.indexOf(v))!=-1)
{
hasCycle=true;
System.out.print("Cycle:");
while(j {
System.out.print(trace.get(j)+" ");
j++;
}
System.out.print("
");
return;
}
return;
}
visited[v]=1;
trace.add(v);

for(int i=0;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(1);
if(!tc.hasCycle)
System.out.println("No Cycle.");
}
}


실행:
C:\java>java TestCycle
Cycle:4 2 5
Cycle:1 3 4 2 5 6 0
Cycle:2 5 6 0
Cycle:2 5 6
원본 코드:

좋은 웹페이지 즐겨찾기