这是
代码不完整
也没有经过测试。它可能有效,也可能无效,但它无论如何都会引导你。
Node n;
Edge e;
String[] splittedLine;
String[] splittedEdge;
HashMap<String, Node> stationNumberToNode = new HashMap<>();
List<String> lines = Files.readAllLines(new File("path/to/file.txt").getPath());
for(String line : lines){
splittedLine = line.split(" ");
if((n = stationNumberToNode.get(splittedLine[0]) == null){
n = new Node(splittedLine[0]);
stationNumberToNode.put(stationNumberToNode[0], n);
}
for(int i = 1; i < splittedLine.lenght; ++i){
splittedEdge = splittedLine[i].split(",");
e = new Edge(splittedEdge[0], splittedEdge[1]);
n.addEdge(e);
}
}
Node n;
Edge e;
String[] splittedLine;
String[] splittedEdge;
HashMap<String, Node> stationNumberToNode = new HashMap<>();
理想情况下,您应该始终声明变量
外部
HashMap
这里使用的是覆盖您的输入不总是分组的情况,并且您避免每次都必须执行列表搜索。
List<String> lines = Files.readAllLines(new File("path/to/file.txt").getPath());
一次读取文件上的所有行。或者,根据问题的要求,您可以使用
Scanner
喜欢开
this anwer
但是,你必须改变在这些行上迭代的方式。
splittedLine = line.split(" ");
分割“”上的行,因为输入文件格式良好。
if((n = stationNumberToNode.get(splittedLine[0]) == null){
n = new Node(splittedLine[0]);
stationNumberToNode.put(stationNumberToNode[0], n);
}
检查当前节点是否已在
哈希图
n
。否则,它将创建一个
Node
使用当前id并将其添加到
.
for(int i = 1; i < splittedLine.lenght; ++i){
splittedEdge = splittedLine[i].split(",");
e = new Edge(splittedEdge[0], splittedEdge[1]);
n.addEdge(e);
}
splittedLine
从索引1开始。
对于每个边缘数据,我们根据“,”(来自您的输入文件)进行分割,而
splittedEdge[0]
将是目标id和
splittedEdge[1]
将是到达目的地的成本。我们创建了一个
Edge
到
节点