深度优先遍历 java

 

以下是java代码

package Map;

public class DepthFirstSearch{
	//定点集合
	private String points[] = {"A","B","C","D","E","F","G","H","I"};
	//是否访问
	private boolean visited[] = new boolean[9];
	//地图
	private int map[][] = new int[9][9];
	//最大值
	private int max = Integer.MAX_VALUE;
	
	//创建地图
	private int[][] createMap(){
		int map[][] = {
				{max,  1,max,max,max,  1,max,max,max},
				{max,max,  1,max,max,max,  1,max,  1},
				{max,  1,max,  1,max,max,max,max,  1},
				{max,max,  1,max,  1,max,  1,  1,  1},
				{max,max,max,  1,max,  1,max,  1,max},
				{  1,max,max,max,  1,max,  1,max,max},
				{max,  1,max,  1,max,  1,max,  1,max},
				{max,max,max,  1,  1,max,  1,max,max},
				{max,  1,  1,  1,max,max,max,max,max}
				
		};
		
		return map;
	}
	//初始化参数
	public void init(){
		this.map = this.createMap();
	}
	//深度遍历开始
	public void dsf(){
	  for(int i = 0 ; i < this.map[0].length ; i++){
		  if(!this.visited[i]){ //该顶点未访问
			  this.dfsMain(this.map, i);
		  }
	  }
	  
	}
	
	//深度遍历算法
	public void dfsMain(int[][] map,int i){
		System.out.print(this.points[i] + " ");	
		this.visited[i] = true;
		for(int j = 0 ; j < this.map[0].length ; j++){
			if(map[i][j]==1&&!this.visited[i]){
				this.dfsMain(map, j);
			}
		}
	}
	
	public static void main(String args[]){
		DepthFirstSearch depthFirstSearch = new DepthFirstSearch();
		depthFirstSearch.init();
		depthFirstSearch.dsf();
	}
	
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值