我试图找到寻找朋友的最短路径。如果 X 想连接到 Y,我想打印出朋友的最短路径,以便 X 到达 Y。每次运行代码时,我都会得到 null。
公共无效最短(字符串优先,字符串目标){
HashMap<String, String> prev = new HashMap<String, String>();
Queue<PersonNode> q = new LinkedList<PersonNode>();
PersonNode firstPerson = hash.get(first);
firstPerson.visited = true;
prev.put(first, first + " ");
q.add(firstPerson);
while(!q.isEmpty()){
PersonNode curr = q.remove();
if(!curr.visited){
curr.visited = true;
if(curr.equals(target)){
break;
}
else{
for(int i =0; i < curr.list.size(); i++){
if(curr.list.get(i).visited = false){
q.add(curr.list.get(i));
curr.list.get(i).visited = true;
prev.put(curr.list.get(i).name, prev.get(curr.list.get(i).name) + curr.list.get(i));
}
}
}
if(!curr.equals(target)){
System.out.println("They have no connections");
}
}
}
System.out.println(prev.get(target));
}