我正在爲學校開發一個項目,該項目要求我們找到兩點之間的最短路徑。基本上我使用廣度優先搜索遍歷圖形,然後使用地圖來跟蹤每個城市的前任。我的想法是,當我到達最後時,我將使用邊緣圖來找出城市是如何得到並基本上是向後的。但是,當我試圖從地圖中提取值時,我所得到的值都是null,即使當我打印出內容時,它也會顯示出有些東西。如果有人能幫助我追蹤這個問題,我將不勝感激。從地圖中添加到堆棧
輸入文件的內容與每個城市和它的鄰居:
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());
}
}
}
我們可以看到您的數據集嗎?終端節點可能無法從起始節點到達,這可以解釋您的錯誤。 – Hbcdev 2012-08-02 18:29:16
這是你在找什麼? – Eric 2012-08-02 18:31:55
Hbcdev說什麼。如果end從start開始是不可到達的,那麼從start開始到達的任何節點都不會有edge,因此edge.get(end)將爲null。 – Soronthar 2012-08-02 18:47:44