1、图的遍历--深度优先搜索
import java.util.Scanner ;public class Map{ static int n ; static int m ; static int[] book ; static int[][] e ; public static void mapDfs(int cur){ //深度优先搜索思想核心; System.out.print(cur + " ") ; for (int i=1;i<=n;i++) { if (e[cur][i]==1 && book[i]==0) { book[i] = 1 ; mapDfs(i) ; } } } public static void main(String[] args){ //测试; Scanner sc = new Scanner(System.in) ; System.out.println("please input the number of nodes:") ; n = sc.nextInt() ; book = new int[n+1] ; e = new int[n+1][n+1] ; for (int i=1;i<=n;i++) { for (int j=1;j<=n;j++) { if (i==j) { e[i][j] = 0 ; }else{ e[i][j] = 99999999 ; } } } System.out.println("please input the number of edges:") ; m = sc.nextInt() ; for (int i=1;i<=m;i++) { int a = sc.nextInt() ; int b = sc.nextInt() ; e[a][b] = 1 ; e[b][a] = 1 ; } book[1] = 1 ; mapDfs(1) ; }}
2、图的遍历--广度优先搜索
import java.util.Scanner ;public class Map02{ public static void main(String[] args){ Scanner sc = new Scanner(System.in) ; System.out.println("please input the number of nodes:") ; int n = sc.nextInt() ; int[] book = new int[n+1] ; int[][] e = new int[n+1][n+1] ; int[] que = new int[n+1] ; int head = 1 ; int tail = 1 ; for (int i=1;i<=n;i++) { for (int j=1;j<=n;j++) { if (i==j) { e[i][j] = 0 ; }else{ e[i][j] = 99999999 ; } } } System.out.println("please input the number of edges:") ; int m = sc.nextInt() ; for (int i=1;i<=m;i++) { int a = sc.nextInt() ; int b = sc.nextInt() ; e[a][b] = 1 ; e[b][a] = 1 ; } que[tail] = 1 ; book[tail] = 1 ; tail++ ; while(headn) { break ; } } head++ ; } for (int i=1;i