图的建立详细解析

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;

public class test35 {

    //点的定义
    public static class Node{
        public int value;//点上的值也就是编号
        public int in;//进去的边有多少
        public int out;//出去的边有多少
        public ArrayList<Node> nexts;//直接邻居,由自己出发能到达的点
        public ArrayList<Edge> edges;//边的集合

        public Node(int value){
            this.value =value;
            in =0;
            out =0;
            nexts = new ArrayList<>();
            edges = new ArrayList<>();
        }
    }

    //边的定义
    public static class Edge{
        public int weight;//权重
        public Node from;
        public Node to;

        public Edge(int weight , Node from , Node to){
            this.weight = weight;
            this.from = from;
            this.to = to;
        }
    }

    //图的定义
    public static class Graph{
        public HashMap<Integer ,Node> nodes;//编号为多少的点那个点的结构是什么
        public HashSet<Edge> edges;//所有的边装在边集里

        public Graph(){
            nodes = new HashMap<>();
            edges = new HashSet<>();
        }
    }

    //形成图结构
    //传进来二维数组,每行有三个值,分别为权重,from和to这三个属性代表了每个点的结构
    public static Graph createGraph(Integer[][] matrix) {
        Graph graph = new Graph();

        for (int i = 0; i < matrix.length; i++) {
            //建立数据
            Integer weight = matrix[i][0];
            Integer from = matrix[i][1];
            Integer to = matrix[i][2];

            //如果图里没有from这个点,就新建
            if (!graph.nodes.containsKey(from)) {
                graph.nodes.put(from, new Node(from));
            }
            //如果图里没有to这个点,就新建
            if (!graph.nodes.containsKey(to)) {
                graph.nodes.put(to, new Node(to));
            }
            //起始点和出发点
            Node fromNode = graph.nodes.get(from);
            Node toNode = graph.nodes.get(to);

            //表达边
            Edge newEdge = new Edge(weight, fromNode, toNode);

            fromNode.nexts.add(toNode);
            fromNode.out++;
            toNode.in++;
            fromNode.edges.add(newEdge);
            graph.edges.add(newEdge);

        }
        return graph;
    }
}
  • 18
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值