图的创建以及一些简单方法

代码
public class Main {
    //用集合存储各个顶点
    static ArrayList<String> vertexList;
    //用二维数组存储各个边(邻接矩阵)
    static int[][] edges;
    //保存边的数目
    static int numOfEdges = 0;

    public static void main(String[] args) {
        String[] vertexs = {"A","B","C","D","E"};

        createGraph(5);

        for (int i = 0;i < vertexs.length;i++){
            insertVertex(vertexs[i]);
        }

        insertEdge(0,1,1);
        insertEdge(0,2,1);
        insertEdge(1,2,1);
        insertEdge(1,3,1);
        insertEdge(1,4,1);
        show();
    }

    //初始化图
    public static void createGraph(int edgeNums){
        vertexList = new ArrayList<String>();
        edges = new int[edgeNums][edgeNums];
        numOfEdges = edgeNums;
    }

    //添加顶点
    public static void insertVertex(String oneVertex){
        vertexList.add(oneVertex);
    }

    //添加边
    public static void insertEdge(int v1,int v2,int weight){
        edges[v1][v2] = weight;
        edges[v2][v1] = weight;
        numOfEdges++;
    }

    //返回节点的数目
    public static int getNumOfVertex(){
        return vertexList.size();
    }

    //返回边的数目
    public static int getNumOfEdges(){
        return numOfEdges;
    }

    //返回下标为i的点的数据
    public static String getValueByIndex(int index){
        return vertexList.get(index);
    }

    //返回某一边的权值
    public static int getWeightByV1V2(int v1,int v2){
        return edges[v1][v2];
    }

    public static void show(){
        for (int[] temp: edges){
            System.out.println(Arrays.toString(temp));
        }
    }
}

结果

[0, 1, 1, 0, 0]
[1, 0, 1, 1, 1]
[1, 1, 0, 0, 0]
[0, 1, 0, 0, 0]
[0, 1, 0, 0, 0]
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值