图 类
包含一个存有所有节点和编号的HashMap
和一个存有所有边的 HashSet
public class Graph {
public HashMap<Integer,Node> nodes;//所有的节点,和节点编号。
public HashSet<Edge> edges;//所有的边
public Graph() {
nodes = new HashMap<Integer,Node>();
edges = new HashSet<Edge>();
}
}
边 类
weight 代表 一条边的权值
from 开始的节点
to 边指向的节点
public 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;
}
}
顶点 类
in代表他的入度
out 代表他的出度
nexts 代表所有已本节点为出度的邻居节点
edges 代表所有已本节点为出度的边
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<Node>();
edges = new ArrayList<Edge>();
}
}
在面试时,面试官经常给的图一般是
[7,1,2]
[5,1,3]
[4,2,6]
]
一个二维数组,代表,
开始节点为1,结束节点为2的权值为7的一条边
开始节点为1,结束节点为3的权值为5的一条边
开始节点为2,结束节点为2的权值为6的一条边
需要转换一下
public static Graph createGraph(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);
fromNode.out++;
toNode.in++;
fromNode.edges.add(newEdge);
graph.edges.add(newEdge);
}
return graph;
}