6、Graph

图的存储方式

邻接表法:
6、Graph_第1张图片
邻接矩阵法:
6、Graph_第2张图片

import java.util.HashMap;
import java.util.HashSet;
public class Graph {
   
	public HashMap<Integer,Node> nodes;
	public HashSet<Edge> edges;

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

import java.util.ArrayList;

public 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 ArrayList edges
6、Graph_第3张图片
A属于a和b,B属于c,C不属于任何边

将给定数据形式转换成习惯的数据类型


public class GraphGenerator {
   

	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];
			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);
			fromNode.out++

你可能感兴趣的:(左神算法,数据结构)