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