图的创建和深度优先遍历

public class GraphMatrix { private static final int MAXNUM = 20; private static final int MAXVALUE = 65535; //顶点信息 private String[] vertex = new String[MAXNUM]; //图的类型,无向图 -0  有向图-1 private int graphType ; //顶点数量 private int vertexNum ; //边的数量 private int edgeNum; //边的权 private int[][] edgeWeight = new int[MAXNUM][MAXNUM]; //遍历标志 private int[] isTravel = new int[MAXNUM]; public void init(){ Scanner scan = new Scanner(System.in); System.out.println(“请输入顶点数量(小于20)”); vertexNum = scan.nextInt(); while(vertexNum <= 0 || vertexNum >20 ){ System.out.println(“请输入顶点数量(小于20)”); vertexNum = scan.nextInt(); } //选择图类型 System.out.println(“请输入图类型 0-无向图  1-有向图”); graphType = scan.nextInt(); while(graphType != 0 && graphType != 1){ System.out.println(“请输入图类型 0-无向图  1-有向图”); graphType = scan.nextInt(); } System.out.println(“请输入各个顶点信息”); for(int i = 0; i < vertexNum; i++){ System.out.println(“第”+(i+1)+”个顶点”); String s = scan.next(); vertex[i] = s; } System.out.println(“请输入边的数量”); edgeNum = scan.nextInt(); int maxEdgeNum =0; if(graphType == 0){ maxEdgeNum = vertexNum * (vertexNum – 1) / 2; }else{ maxEdgeNum = vertexNum * (vertexNum – 1); } while(edgeNum < 0 || edgeNum > maxEdgeNum){ System.out.println(“请输入边的数量(0-“+maxEdgeNum+”)”); edgeNum = scan.nextInt(); } //初始化边的权信息,先将各边的权设为MAXVALUE for(int i = 0 ; i < vertexNum ; i++){ for(int j = 0; j < vertexNum; j++){ edgeWeight[i][j] = MAXVALUE; } } System.out.println(“输入各边的顶点和权值、”); for(int i = 0; i < edgeNum; i++){ System.out.println(“第”+(i+1)+”条边”); String start = scan.next(); String end = scan.next(); int x = findVertexIndex(start); int y = findVertexIndex(end); edgeWeight[x][y] = scan.nextInt(); if(graphType == 0){ edgeWeight[y][x] = edgeWeight[x][y]; } } } private int findVertexIndex(String s){ for(int i = 0 ; i < vertex.length ; i++){ if(s.equals(vertex[i])){ return i; } } return -1; } private  void deepTra_self(int n){ if(n < 0 || n >= vertex.length){ System.out.println(“无此节点”); } System.out.println(vertex[n]); isTravel[n] = 1; for(int i = 0; i < vertexNum; i ++){ if(edgeWeight[n][i] != MAXVALUE && isTravel[i] ==0){ deepTra_self(i); } } //System.out.println(vertex[n]); } public void deepTra(int n){ deepTra_self(n-1); } }

    原文作者:数据结构之图
    原文地址: https://blog.csdn.net/gengjianchun/article/details/78443092
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞