以下是问题:
二维数组关系[n] [2]表示节点之间的关系,例如关系[0]等于{2,4},因此节点2和节点4之间存在邻接关系,并且包含没有循环关系。
我想将树结构保存在hashmap中,所以我尝试编写如下代码:
Map<Integer, LinkedList<Integer>> graph = new HashMap<Integer, LinkedList<Integer>>();
for (int i = 0; i < n; i++) {
int A = relation[i][0];
int B = relation[i][1];
if (graph.get(A) == null) {
List<Integer> tempList = new LinkedList();
tempList.add(B);
graph.put(A, tempList);
} else {
graph.get(A).add(B);
}
if (graph.get(B) == null) {
List<Integer> tempList = new LinkedList();
tempList.add(A);
graph.put(B, tempList);
} else {
graph.get(B).add(A);
}
}
显然它不起作用,但我不知道如何解决它,有人可以帮助我吗?谢谢!
答案 0 :(得分:1)
代码有效(我测试过),但输入错误很少。
LinkedList
按原样声明,地图中的值应该是List
。
但是在这里,你提出了一些List<Integer> tempList = //[...];
[...]
//Compiler will complain that tempList is a List but a LinkedList is expected.
graph.put(A, tempList);
:
LinkedList<Integer> tempList = new LinkedList<>();
所以要么像这样创建一些LinkedList:
Map
或声明您的List
将某些Map<Integer, List<Integer>>
视为值:
Map.computeIfAbsent
注意:从Java 8开始,您可以像这样使用Map<Integer, LinkedList<Integer>> graph = new HashMap<>();
for (int i = 0; i < n; i++) {
int A = relation[i][0];
int B = relation[i][1];
graph.computeIfAbsent(A, k-> new LinkedList<>()).add(B);
graph.computeIfAbsent(B, k-> new LinkedList<>()).add(A);
}
:
function Detal(date1, date2){
window.location.href = "data/iframe.html?Detal_1=" +date1+ "&Detal_2=" +date2;
}
答案 1 :(得分:0)
以这种方式试试。处理数组确实多次定义边(即可能)时的情况:
// 1
// / | \
// 2 3 4
// / / \ \
// 5 6 7 8
//
public static void main(String[] args) {
int[][] tree = new int[][] {
{1, 2}, {1, 3}, {1, 4},
{2, 5}, {3, 6}, {3, 7}, {4, 8} };
Map<Integer, List<Integer>> map = new HashMap<>();
for (int[] node : tree) {
addEdge(map, node[0], node[1]);
addEdge(map, node[1], node[0]);
}
System.out.println(map);
}
private static void addEdge(Map<Integer, List<Integer>> map, int key, int value) {
List<Integer> edges = map.computeIfAbsent(key, k -> new LinkedList<>());
if (! edges.contains(value)) edges.add(value);
}
<强>输出强>
{1=[2, 3, 4], 2=[1, 5], 3=[1, 6, 7], 4=[1, 8], 5=[2], 6=[3], 7=[3], 8=[4]}