数据结构实验之图论二:图的深度遍历-java代码
1 import java.util.Scanner; 2 3 public class Main { 4 5 public static int[] visit = new int[1000]; 6 public static int[][] map = new int[1000][1000]; 7 8 public static void main(String[] args) { 9 Scanner input = new Scanner(System.in); 10 int T = input.nextInt(); 11 for (int x = 0; x < T; x++) { 12 int n = input.nextInt(), m = input.nextInt(); 13 for (int i = 0; i <n; i++) { 14 for(int j=0;j<n;j++) 15 map[i][j] = 0; 16 visit[i] = 0; 17 } 18 for (int i = 0; i < m; i++) { 19 int a = input.nextInt(); 20 int b = input.nextInt(); 21 map[a][b] = map[b][a] = 1; 22 } 23 System.out.print(0); 24 DFS(0, n); 25 System.out.println(); 26 } 27 } 28 29 public static void DFS(int temp, int m) { 30 visit[temp] = 1; 31 for (int i = 0; i <m; i++) { 32 if (visit[i] == 0 && map[temp][i] == 1) { 33 System.out.print(" " + i); 34 DFS(i, m); 35 } 36 } 37 } 38 }