欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

基于邻接矩阵存储的图的深度优先遍历代码(Java语言实现)

程序员文章站 2022-05-20 16:48:44
...
package temp;

import java.util.Scanner;

public class Test {  //图的深度优先遍历(图的存储基于邻接表)
	public static void main(String[] args) {
		String[] arr = {"a","b","c","d","e"};
		MGraph mg = new MGraph(arr, 5, 5);  //5个顶点5条边
		mg.DFSTraverse(3);  //从"d"开始遍历
	}
}

class MGraph {
	final int MaxSize = 10;  //图中顶点的最多个数
	private int vertexNum,arcNum;  //图的顶点数和边数
	private String[] vertex = new String[MaxSize];  //存放顶点内容的数组
	private int[][] arc = new int[MaxSize][MaxSize];  //存放边的数组
	private int[] visited = new int[MaxSize];  //存放每个顶点被访问情况
	
	public int getVertexNum() {  //获取顶点数
		return vertexNum;
	}
	
	public void setVertexNum(int vertexNum) {  //设置顶点数
		this.vertexNum = vertexNum;
	}
	
	public int getArcNum() {  //获取边数
		return arcNum;
	}
	
	public void setArcNum(int arcNum) {  //设置边数
		this.arcNum = arcNum;
	}
	
	public String[] getVertex() {  //获取顶点数组
		return vertex;
	}
	
	public void setVertex(String[] vertex) {  //设置顶点数组
		this.vertex = vertex;
	}
	
	public MGraph() {}
	
	public MGraph(String [] arr, int n, int e) {  //构造函数,建立具有n个顶点e条边的图
		vertexNum = n;
		arcNum = e;
		for (int i = 0; i < vertexNum; i++) {
			vertex[i] = arr[i];
			visited[i] = 0;
		}
		
		for (int i = 0; i < vertexNum; i++)  //初始化邻接矩阵
			for (int j = 0; j < vertexNum; j++)
				arc[i][j] = 0;  //置所有顶点间的有边标志为0,即任意两个顶点之间都没有边
		
		setArc(arcNum, arc);
	}
	
	public static void setArc(int arcNum, int[][] arc) {  //从键盘录入边的信息
		Scanner sc = new Scanner(System.in);
		int i, j;
		for (int k = 0; k < arcNum; k++) {
			System.out.println("请输入第" + (k+1) + "条边依附的两个顶点的编号:");
			i = sc.nextInt();
			j = sc.nextInt();
			arc[i][j] = 1;
			arc[j][i] = 1;
		}
	}
	
	public void DFSTraverse(int v) {  //从顶点v开始的深度优先遍历
		System.out.print(vertex[v] + "\t");
		visited[v] = 1;
		
		for (int i = 0; i < vertexNum; i++) {
			if (visited[i] == 0 && arc[v][i] == 1)
				DFSTraverse(i);
		}
	}
}

运行截图:
基于邻接矩阵存储的图的深度优先遍历代码(Java语言实现)