博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
图的遍历(深度优先与广度优先搜索两种方案)
阅读量:4465 次
发布时间:2019-06-08

本文共 1762 字,大约阅读时间需要 5 分钟。

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
n) { break ; } } head++ ; } for (int i=1;i

  

转载于:https://www.cnblogs.com/lshl/p/5926363.html

你可能感兴趣的文章
npm和Node.js简介
查看>>
Spring AOP无法拦截Controller的原因
查看>>
Windows双系统
查看>>
Microsoft Project项目管理工具
查看>>
软件设计师-算法
查看>>
小米手机安装Google框架
查看>>
honpeyhonepy
查看>>
netaddr网络地址工具python
查看>>
OSI7层模型和网络排错、网络安全
查看>>
hash文件-对文件进行数字签名
查看>>
TCP_Wrappers基础知识介绍
查看>>
Central Post Office (Shiraz University Local Contest 2011 ) 树状dp
查看>>
51Nod - 1031 骨牌覆盖
查看>>
回顾环信使用
查看>>
JavaScript--函数对象的属性caller与callee
查看>>
特殊字符大全
查看>>
SQL - SQL 连接 JOIN 例解。(左连接,右连接,全连接,内连接,交叉连接,自连接)[转]...
查看>>
《learning hard C#学习笔记》读书笔记(20)异步编程
查看>>
动态创建Struct实例
查看>>
Jsp通过JDBC连接到SQL Server2008数据库遇到的几个问题
查看>>