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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了图的遍历(深度优先与广度优先搜索两种方案)相关的知识,希望对你有一定的参考价值。

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() ;
	}
}

  

以上是关于图的遍历(深度优先与广度优先搜索两种方案)的主要内容,如果未能解决你的问题,请参考以下文章

图的深度/广度优先遍历C语言程序

深度优先遍历与广度优先遍历的区别

图 - 深度优先遍历

深度优先搜索法和广度优先搜索法

图的遍历之 深度优先搜索和广度优先搜索

数据结构与算法图遍历算法 ( 深度优先搜索 DFS | 深度优先搜索和广度优先搜索 | 深度优先搜索基本思想 | 深度优先搜索算法步骤 | 深度优先搜索理论示例 )