我正在为学校做一个项目,该项目要求我们找到两点之间的最短路径。基本上我使用广度优先搜索来遍历图表,然后使用地图来跟踪每个城市的前身。我的想法是,当我到达终点时,我将使用边缘地图来找出一个城市是如何到达的,并且基本上是向后工作。但是,当我尝试从地图中提取值时,我得到的只是空值,即使当我打印出内容时它表明那里有东西。如果有人可以帮助我找出问题所在,我将不胜感激。
每个城市及其邻居的输入文件内容:
basic
Bismark Fargo
Minneapolis Chicago
StPaul Chicago
Minneapolis StPaul
Minneapolis Fargo
Fargo GrandForks
代码(更正版本,因此此代码将不再出现所描述的问题):
import java.util.*;
import java.io.*;
public class BFSBasics {
public static void main(String[] args) throws FileNotFoundException {
Map<String, List<String>> graph = new HashMap<>();
openFile(graph, args[0]);
String start = args[1];
String end = args[2];
BFS(graph, start, end);
}
public static void openFile(Map<String,List<String>> graph,
String file)
throws FileNotFoundException{
Map<String,List<String>> aGraph = new HashMap<>();
try (Scanner scan = new Scanner(new File(file))){
if(!scan.next().equals("basic")){
System.err.println("File cannot be read.");
System.exit(1);
}else{
while(scan.hasNext()){
String city1 = scan.next();
String city2 = scan.next();
addEdge(graph, city1, city2);
addEdge(graph, city2, city1);
}
}
}
}
private static void addEdge(Map<String, List<String>> graph, String city1,
String city2){
List<String> adjacent = graph.get(city1);
if(adjacent == null){
adjacent = new ArrayList<>();
graph.put(city1, adjacent);
}
adjacent.add(city2);
}
public static void BFS(Map<String, List<String>> graph, String start,
String end) {
boolean done = false;
//cities that still need to be worked on
Queue<String> work = new ArrayDeque<>();
//cities that have already been seen
Set<String> seen = new HashSet<>();
//cities predecessor i.e. how it was gotten to
Map<String, String> edges = new HashMap<>();
LinkedList<String> path = new LinkedList<>();
String city = start;
work.add(start);
while (!done && !work.isEmpty()) {
city = work.remove();
for (String s : graph.get(city)) {
if (!seen.contains(s)) {
edges.put(s, city);
work.add(s);
seen.add(s);
if (s.equals(end)) {
done = true;
}
}
}
}
//Work backwards through the edges map and push onto the path stack
path.push(end);
String temp = edges.get(end);
while(!temp.equals(start)){
path.push(temp);
temp = edges.get(path.peek()};
}
path.push(start);
//print out the path
while(!path.isEmpty()){
System.out.println(path.pop());
}
}
}