題目見 POJ 3895html
下面是我修改過的代碼,網上原文是:https://www.cnblogs.com/gxilizq/p/3533472.htmljava
package pro.yao9_22; import java.util.ArrayList; import java.util.LinkedList; import java.util.Scanner; /** * * @author XASW 1 7 8 3 4 1 4 1 3 7 1 2 7 7 5 5 6 6 2 #1 4 1 7 9 3 4 1 4 1 5 1 3 7 1 2 7 7 5 5 6 6 2 5?4? */ public class Main { static int T,N,M; static int answer; static boolean[] visited; //記錄已訪問標誌 static LinkedList<ArrayList<Integer>> item ; //圖的 鄰接表存儲 static int[] vNum; //保存訪問的位置,已經訪問了幾個 public static void main(String[] args) { Scanner sc = new Scanner(System.in); T = sc.nextInt(); for (int t = 0; t < T; t++) { answer = 0; N = sc.nextInt(); M = sc.nextInt(); visited = new boolean[N+1]; vNum = new int[N+1]; item = new LinkedList<ArrayList<Integer>>(); for (int i = 0; i <= N; i++) { item.add(new ArrayList<Integer>()); } for (int m = 0; m < M; m++) { int s = sc.nextInt(); int e = sc.nextInt(); item.get(s).add(e); item.get(e).add(s); } // printArr(item); for (int i = 1; i < item.size(); i++) { if(!visited[i]) dfs(i,1); } System.out.println(answer); } sc.close(); } private static void dfs(int s, int t) { visited[s] = true; vNum[s] = t; for (int i = 0; i < item.get(s).size(); i++) { int ns = item.get(s).get(i); if(!visited[ns]) {//下一個已經訪問了,就是有環了, 這裏是沒有訪問 則繼續下一個 dfs(ns,t+1); }else { if(vNum[s]-vNum[ns]>1 //相鄰兩個不能算做環 &&answer<vNum[s]-vNum[ns]+1 ){ answer = vNum[s]-vNum[ns]+1; } } } // visited[s] = false; } private static void printArr(LinkedList<ArrayList<Integer>> item2) { int s=0; for (ArrayList<Integer> arrayList : item2) { System.out.print(s+"===>>>"); for (Integer i : arrayList) { System.out.print(i+","); } System.out.println(""); s++; } } }