目錄
1 問題描述
Problem Description
歐拉回路是指不令筆離開紙面,可畫過圖中每條邊僅一次,且可以回到起點的一條回路。現給定一個圖,問是否存在歐拉回路?
Input
測試輸入包含若干測試用例。每個測試用例的第1行給出兩個正整數,分別是節點數N ( 1 < N < 1000 )和邊數M;隨后的M行對應M條邊,每行給出一對正整數,分別是該條邊直接連通的兩個節點的編號(節點從1到N編號)。當N為0時輸入結
束。
束。
Output
每個測試用例的輸出占一行,若歐拉回路存在則輸出1,否則輸出0。
Sample Input
3 3
1 2
1 3
2 3
3 2
1 2
2 3
0
Sample Output
1
0
2 解決方案
具體代碼如下:
package com.liuzhen.practice; import java.util.ArrayList; import java.util.Scanner; public class Main { public static int MAX = 1000; public static int[][] map = new int[MAX][MAX]; //輸入圖 public static ArrayList<Integer> result = new ArrayList<Integer>(); //用於存放最終輸出結果 //判斷給定圖的每個頂點的度是否均為偶數 public boolean judge(int[] degree) { for(int i = 0;i < degree.length;i++) { if(degree[i] % 2 != 0) return false; } return true; } //使用BFS遍歷,判斷給定圖是否為連通圖 public boolean bfs(int n) { boolean[] used = new boolean[n]; ArrayList<Integer> list = new ArrayList<Integer>(); list.add(0); used[0] = true; while(!list.isEmpty()) { int temp = list.get(0); list.remove(0); for(int i = 0;i < n;i++) { if(!used[i] && map[temp][i] != 0) { used[i] = true; list.add(i); } } } for(int i = 0;i < n;i++) { if(used[i] == false) return false; } return true; } public static void main(String[] args) { Main test = new Main(); Scanner in = new Scanner(System.in); while(true) { int n = in.nextInt(); //輸入圖的頂點數 if(n == 0) break; int m = in.nextInt(); //輸入圖的邊數目 int[] degree = new int[n]; //用於計算輸入圖的每個頂點的度 for(int i = 0;i < m;i++) { int a = in.nextInt(); int b = in.nextInt(); map[a - 1][b - 1] = 1; map[b - 1][a - 1] = 1; degree[a - 1]++; degree[b - 1]++; } if(test.judge(degree) && test.bfs(n)) result.add(1); else result.add(0); } for(int i = 0;i < result.size();i++) System.out.println(result.get(i)); } }
運行結果:
3 3 1 2 1 3 2 3 3 2 1 2 2 3 0 1 0
參考資料:
1. 歐拉回路