Java实现图的深度优先遍历

深度优先遍历算法如下:

/*其中matirx为图的邻接矩阵,Vertex为自定义的顶点类,
start为指定的起始顶点,list2用来存储深度优先遍历的顶点序列*/
static void dfs(int matrix[][],List<Vertex> list,int start,List<Integer> list2){
	int length = matrix.length;
	Vertex node = list.get(start);
	list2.add(node.getIndex());
	node.setVisited(true);
	for(int i = 0;i<length;i++){
		int weight = matrix[start][i];
		if(weight != 0){
			if(list.get(i).isVisited()){
				continue;
			}
			else{
				dfs(matrix,list,i,list2);
			}
		}
		else{
			continue;
		}
	}
}
class Vertex{
	int index;
	boolean  visited;
	Vertex(int index){
		this.index = index;
	}
	int getIndex(){
		return index;
	}
	void setIndex(int index){
		this.index = index;
	}
	boolean isVisited(){
		return visited;
	}
	void setVisited(boolean visited){
		this.visited= visited;
	}
}

主方法(测试用):

public static void main(String args[]){
		int matrix[][]={
		{0,1,1,0,0,0,1},
		{1,0,0,0,0,1,0},
		{1,0,0,1,1,0,0},
		{0,0,1,0,0,0,0},
		{0,0,1,0,0,0,0},
		{0,1,0,0,0,0,0},
		{1,0,0,0,0,0,0}
		};
		List<Vertex>list = new ArrayList<Vertex>();
		for(int i = 0 ;i<matrix.length;i++){
			list.add(new Vertex(i));
		}
		List<Integer>list2 = new ArrayList<Integer>();
		dfs(matrix,list,0,list2);
		System.out.print(list2);
	}

上述邻接矩阵所表示的图如下:
在这里插入图片描述
测试结果如下:
在这里插入图片描述

posted on 2019-06-30 01:34  107国道道长  阅读(820)  评论(0编辑  收藏  举报

导航