码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-10-01 21:52:56      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:

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

  

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

标签:

原文地址:http://www.cnblogs.com/lshl/p/5926363.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!