首页 > 代码库 > 图的遍历(深度优先与广度优先搜索两种方案)

图的遍历(深度优先与广度优先搜索两种方案)

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(head<tail){                            //广度优先搜索思想核心			int cur = que[head] ;			for(int i=1;i<=n;i++){				if (e[cur][i]==1 && book[i]==0) {					que[tail] = i ;					tail++ ;					book[i] = 1 ;				}				if (tail>n) {					break ;				}			}			head++ ;		}		for (int i=1;i<tail;i++) {			System.out.print(que[i] + " ") ;		}		System.out.println() ;	}}

  

图的遍历(深度优先与广度优先搜索两种方案)