什么是图结构:
图的基本概念:
代码实现准备数据:
代码实现:
/** * @PackageName: * @author: * @date:2022/7/30 */ public class ChartTable { static Scanner input = new Scanner(System.in); //创建邻接矩阵 static void CreateGraph(GraphMatrix GM){ int i,j,k; //权 int weight; //边的起始顶点 char EstartV,EendV; System.out.println("输入图中各顶点信息"); for (i=0;i<GM.vertexNum;i++){ System.out.println("第"+(i+1)+"个顶点"); //保存到各顶点数组元素中 GM.Vertex[i] = (input.next().toCharArray())[0]; } System.out.println("输入构成各边的顶点及权值"); for (k=0;k<GM.edgeNum;k++){ System.out.println("第"+(k+1)+"条边"); EstartV = input.next().charAt(0); EendV = input.next().charAt(0); weight = input.nextInt(); //在已有顶点中查找开始点 for (i=0;EstartV != GM.Vertex[i];i++); //在已有顶点中查找终结点 for (j=0;EendV != GM.Vertex[j];j++); //对应位置保存权值,表示有一条边 GM.EdgeWeigth[i][j] = weight; //如果是无向图 if (GM.GType == 0){ //在对角位置保存权值 GM.EdgeWeigth[j][i] = weight; } } } /** * 清空矩阵 * @param GM */ static void ClearGraph(GraphMatrix GM){ int i,j; for (i=0;i<GM.vertexNum;i++){ for (j=0;j<GM.vertexNum;j++){ GM.EdgeWeigth[i][j] = GraphMatrix.MaxValue; } } } static void OutGraph(GraphMatrix GM){ int i,j; for (j=0;j<GM.vertexNum;j++){ //在第1行输出顶点信息 System.out.printf("\t%c",GM.Vertex[j]); } System.out.printf("\n"); for (i=0;i<GM.vertexNum;i++){ System.out.printf("%c",GM.Vertex[i]); for (j=0;j<GM.vertexNum;j++){ if (GM.EdgeWeigth[i][j] == GraphMatrix.MaxValue){ System.out.printf("\tZ"); }else { System.out.printf("\t%d",GM.EdgeWeigth[i][j]); } } System.out.println(); } } /** * 从第n个节点开始深度遍历图 * @param GM */ static void DeepTraOne(GraphMatrix GM,int n){ int i; //标记该节点已经处理过 GM.isTrav[n] = 1; System.out.printf("->%c",GM.Vertex[n]); //添加处理节点的操作 for (i=0;i<GM.vertexNum;i++){ if (GM.EdgeWeigth[n][i] != GraphMatrix.MaxValue && GM.isTrav[n] == 0){ //递归遍历 DeepTraOne(GM,i); } } } /** * 深度优先遍历 * @param GM */ static void DeepTraGraph(GraphMatrix GM){ int i; //清除各个节点遍历标识 for (i=0;i<GM.vertexNum;i++){ GM.isTrav[i] = 0; } System.out.printf("深度优先遍历"); for (i=0;i<GM.vertexNum;i++){ //若该节点未遍历 if( GM.isTrav[i] == 0){ //调用函数遍历 DeepTraOne(GM,i); } } System.out.printf("\n"); } public static void main(String[] args){ GraphMatrix GM = new GraphMatrix(); System.out.println("输入生成图的类型"); GM.GType = input.nextInt(); System.out.println("输入图的顶点数量"); GM.vertexNum = input.nextInt(); System.out.println("输入图的边数量"); GM.edgeNum = input.nextInt(); ClearGraph(GM); CreateGraph(GM); System.out.println("该图的邻接矩阵数据如下"); OutGraph(GM); DeepTraGraph(GM); } } class GraphMatrix{ static final int MaxNum = 20; static final int MaxValue = 65535; //保存顶点信息 char[] Vertex = new char[MaxNum]; //图的类型:0 无向图,1 有向图 int GType; //顶点的数量 int vertexNum; //边的数量 int edgeNum; //保存边的权 int[][] EdgeWeigth = new int[MaxNum][MaxNum]; //遍历标识 int[] isTrav = new int[MaxNum]; }