使用HashMaps和ArrayList的最短路径(使用BFS)

时间:2012-12-08 00:48:25

标签: arraylist hashmap shortest-path breadth-first-search

我正在努力寻找寻找朋友的最短途径。如果X人想要连接到Y,我想打印出朋友的最短路径,以便让X到达Y.每次运行代码时,我都会得到null。

public void shortest(String first,String target){

    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));
}

1 个答案:

答案 0 :(得分:0)

尝试调试代码。我看到你在循环之外将firstperson.visited设置为true。然后,您从队列中弹出它并忽略它,因为它是true。在你的循环中它是相同的:你将所有被访问的属性设置为true,这将导致它们在运行时从队列中弹出时被忽略

我也在想“他们没有联系”-part不应该在while循环中