只能用java实现
public class Node { public int val; public int in; public int out; public ArrayList<Node> nodes; public ArrayList<Edge> edges; public Node(int val) { this.val=val; in=0; out=0; nodes=new ArrayList<> nodes(); edges=new ArrayList<> edges(); } } public class Edge { public int val; public Node in; public Node out; public Edge(int weight, Node from, Node to) { this.weight = weight; this.from = from; this.to = to; } } public class Graph { public HashMap<Integer,Node> nodes; public HashSet<Edge> edges; public Graph() { nodes = new HashMap<>(); edges = new HashSet<>(); } } package com.Java.Gragh; import java.util.Iterator; import java.util.Set; /** * @program: JAVA * @description: * @author: 王侃 * @create: 2021-02-08 14:20 **/ public class GenerateGraph { public static Graph generateGraph(Integer[][] number) { Graph graph = new Graph(); for (int i = 0; i < number.length; i++) { int val = number[i][0]; int left = number[i][1]; int right = number[i][2]; if (!graph.nodes.containsKey(left)) graph.nodes.put(left, new Node(left)); if (!graph.nodes.containsKey(right)) graph.nodes.put(right, new Node(right)); Node from = graph.nodes.get(left); Node out = graph.nodes.get(right); Edge edge = new Edge(val, from, out); from.edges.add(edge); from.out++; out.in++; from.nodes.add(out); graph.edges.add(edge); } return graph; } public static void main(String[] args) { Integer[][] number={{1,2,3},{1,3,2},{2,2,6}};; Graph graph=new Graph(); graph=generateGraph(number); // Set<Integer> sets = graph.keySet(); // Iterator<Integer> i=sets.iterator(); System.out.println(number.toString()); for(Integer i:graph.nodes.keySet()) { System.out.println("val的值"+graph.nodes.get(i).val); System.out.println("入度"+graph.nodes.get(i).in); System.out.println("出度"+graph.nodes.get(i).out); System.out.print("邻接结点:"); for(Node node:graph.nodes.get(i).nodes) System.out.print(node.val); System.out.print("邻接边:"); for(Edge edge:graph.nodes.get(i).edges) System.out.print(edge.val); } } }