깊이 우선 검색 출력 은 그림 에 있 는 모든 링(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
원본 코드:
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
[전] 자바 로 pdf 를 jpg 그림 으로 변환 하 는 코드이 코드 는 pdf 를 jpg 그림 으로 변환 할 수 있 습 니 다. 그림 이 뚜렷 하 지 는 않 지만 충분히 사용 할 수 있 습 니 다. 표지 의 그림 만 문서 의 미리 보기 그림 을 만 들 고 싶 기 때 문 입 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.