图结构转化

public class GraphStrcture{
    public static class Graph{
		public HashMap<Integer,Node> nodes;//点集,每一个记录着当前点的值和真正的点
		public HashSet<Edge> edges;//边集

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

    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;
		}
	}

	//将不熟悉的图结构转换为熟悉的结构
	//matrix 所有的边  
	// N * 3的矩阵
	// [weight,from节点上的值,to节点上面的值]
	public static Graph creatGraph(Integer[][] matrix){//该图的结构是三列的矩阵,记录出度,入度,权重,如何转化为熟悉的图结构
		Graph graph = new Graph();
		for(int i = 0; i < matrix.length; i++){
			Integer from = matrix[i][0];
			Integer to = matrix[i][1];
			Integer weight = matrix[i][2];//把三个信息取出来
			if(!graph.nodes.containsKey(from)){
				graph.nodes.put(from,new Node(from));
			}
			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);//from的邻居里把to点加上
			fromNode.out++;
			toNode.in++;
			fromNode.edges.add(newEdge);
			graph.edges.add(newEdge);

		}
		return graph;
	}
 
}

将不熟悉的图结构转化为熟悉的图结构模板

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值