一、 邻接矩阵
private int[][] constructGraph(int vertexCount, int[][] edges) {
int[][] adjMat = new int[vertexCount+1][vertexCount+1];
for (int i = 0; i < edges.length; i++) {
adjMat[edges[i][0]][edges[i][1]] = 1;
adjMat[edges[i][1]][edges[i][0]] = 1;
}
return adjMat;
}
二、 邻接表
private List<List<Integer>> constructGraph(int[][] edges) {
List<List<Integer>> graph = new ArrayList<>();
for (int i = 0; i < edges.length; i++) {
List<Integer> head = new ArrayList<>();
for (int node : edges[i]) {
head.add(node);
}
graph.add(head);
}
return graph;
}
三、 邻接表(散列)
private Map<Integer, PriorityQueue<Integer>> constructGraph(List<List<Integer>> edgeList) {
Map<Integer, PriorityQueue<Integer>> graph = new HashMap<>();
for (List<Integer> edge : edgeList) {
graph.computeIfAbsent(edge.get(0), k -> new PriorityQueue<>()).offer(edge.get(1));
}
return graph;
}
如有错误, 望指正, 十分感谢!
|