[英]Entering values inside a nested map
I was thinking of ways to implement an adjacency list for a graph and thought a nested map might be a good idea(because of the fast lookup times) for the outer map I can say map.put but for the inner map which is unnamed how我是否将值放入
Scanner sc = new Scanner(System.in);
Map<Integer,Map<Integer,Integer>> graph = new HashMap<>();
int V = sc.nextInt();
int E = sc.nextInt();
for(int i=0;i<E;i++){
int v1 = sc.nextInt();
int v2 = sc.nextInt();
int w = sc.nextInt();
graph.put(v1, Map.entry(v2, w));
graph.put(v2, Map.entry(v1, w));
}
其中 v1 和 v2 是图的节点/顶点,w 是两个顶点之间的权重/边
有人有什么主意吗? 提前致谢:)
您可以像这样放入图表
if (!graph.contains(v1)) {
grah.put(v1, new HashMap<>());
}
if (!graph.contains(v2)) {
grah.put(v2, new HashMap<>());
}
graph.get(v1).put(v2, w);
graph.get(v1).put(v2, w);
graph.putIfAbsent(v1, new HashMap<>());
graph.get(v1)
graph.get(v1).put(v2, 2)
graph.putIfAbsent(v1, new HashMap<>());
graph.putIfAbsent(v2, new HashMap<>());
graph.get(v1).put(v2, w);
graph.get(v2).put(v1, w);
我不确定你从哪里得到 Map.entry 方法,但通常你会像外部一样创建内部 map 然后把它放进去。像:
Scanner sc = new Scanner(System.in);
Map<Integer,Map<Integer,Integer>> graph = new HashMap<>();
int V = sc.nextInt();
int E = sc.nextInt();
for(int i=0;i<E;i++){
int v1 = sc.nextInt();
int v2 = sc.nextInt();
int w = sc.nextInt();
Map<Integer,Integer> innerMap = new HashMap<>();
innerMap.put(v2, w);
graph.put(v1, innerMap);
Map<Integer,Integer> andAnotherMap = new HashMap<>();
andAnotherMap.put(v2, w);
graph.put(v2, andAnotherMap);
}
当然,将它包装在一个方法中会更干净,所以你最终会得到:
private Map<Integer, Integer> innerMap(int a, int b) {
Map<Integer,Integer> innerMap = new HashMap<>();
innerMap.put(a, b);
return innerMap;
}
...
Scanner sc = new Scanner(System.in);
Map<Integer,Map<Integer,Integer>> graph = new HashMap<>();
int V = sc.nextInt();
int E = sc.nextInt();
for(int i=0;i<E;i++){
int v1 = sc.nextInt();
int v2 = sc.nextInt();
int w = sc.nextInt();
graph.put(v1, innerMap(v2, w));
graph.put(v2, innerMap(v1, w));
}
希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.