【问题标题】:Find shortest path between two locations (Unweighted & Using BFS)查找两个位置之间的最短路径(未加权和使用 BFS)
【发布时间】:2017-04-29 20:50:57
【问题描述】:

使用 BFS 的最短路径

public static LinkedList<String> findShortestPath(String start, String end) {

    LinkedList<String> bfsList = new LinkedList<String>();
    Queue<Actor> queue = new LinkedList<Actor>();
    Map<String, Actor> prev = new HashMap<String, Actor>();
    Actor current = graph.getActorsByName().get(start);

    queue.add(current);
    current.setVisited(true);

    while(!queue.isEmpty()) {

        current = queue.remove();;

        if(current.getName().equals(end)) {

            break;

        } else {

            for(int i = 0; i < current.getFriends().size(); i++) {

                if(current.getFriends().get(i).getVisited() == false) {

                    queue.add(graph.getActorsByName().get(current.getFriends().get(i).getName()));
                    graph.getActorsByName().get(current.getFriends().get(i).getName()).setVisited(true);
                    prev.put(current.getFriends().get(i).getName(), current);

                }

            }

        }

    }

    if(!current.getName().equals(end)) {

        System.out.println("\nThere is no path between " + start + " and " + end);

    }

    for(Map.Entry<String, Actor> entry : prev.entrySet()) {

        String key = entry.getKey();
        bfsList.add(key);

    }

    return bfsList;

}

上面是我用来尝试在图中找到两点之间的最短路径的代码。它没有给我两点之间的正确路径,我不知道为什么。

【问题讨论】:

  • 你怎么知道它工作不正常?你有测试输入吗?任何预期输出和实际输出?您是否有任何基于您的实施的参考资料?
  • @James 是的,我确实有几个测试输入和预期输出;但是为了在这里有意义,我必须提出我的整个程序,即 1000 多行......我只想知道我提供的方法是否会给我两点之间的最短路径。我用于此实现的参考是这样的:stackoverflow.com/questions/1579399/… 我只是在理解使用广度优先搜索找到最短路径背后的算法时遇到了一些麻烦。

标签: java shortest-path breadth-first-search


【解决方案1】:

我已经建立了一个测试平台,我希望一个演员有一个名字和一些朋友。那些直接的朋友也有互惠关系。

在这个测试中,我正在寻找“james”和“mary”之间的最短路径。

import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;

import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import org.junit.Test;

public class ShortestPathTest {

    Map<String, ShortestPath.Actor> graph = new HashMap<>();

    private ShortestPath.Actor newActor(String name, String... friends) {
        ShortestPath.Actor actor = graph.computeIfAbsent(name, k -> new ShortestPath.Actor(name));
        for(String friendsName : friends) {
            ShortestPath.Actor friend = newActor(friendsName);
            actor.addFriend(friend);
            friend.addFriend(actor);
        }
        return actor;
    }

    @Test
    public void findShortestPath() {
        newActor("james", "harry", "luke", "john");
        newActor("harry", "luke", "mary");

        LinkedList<String> shortestPath = ShortestPath.findShortestPath(graph, "james", "mary");
        assertThat(shortestPath, equalTo(Arrays.asList("james", "harry", "mary")));
    }
}

我收到的结果与我的预期不一致,由于某种原因,“mary”位于输出的中间:

java.lang.AssertionError: 
Expected: <[james, harry, mary]>
     but: was <[luke, harry, mary, john]>

比较algorithm you have referenced,我怀疑问题出在这部分(引用算法的):

for(Node node = finish; node != null; node = prev.get(node)) {
    directions.add(node);
}
directions.reverse();

在您的实现中,您已初始化 prev = new HashMap&lt;String, Actor&gt;(),然后添加每个访问过的节点(不仅仅是指示最短路径的节点)。您需要使用prev 作为链表的排序...例如:

    for (Actor node = graph.get(end); node != null; node = prev.get(node.getName())) {
        bfsList.add(node.getName());
    }
    Collections.reverse(bfsList);

用于测试目的的完整更新代码

最短路径实现

仅对原始帖子进行了少量修改:

  • 输入graph作为参数
  • 通过提取查看变量简化内部循环中的逻辑
  • 如果找不到路径,则返回空列表
  • 修复了分析找到的最短路径的哈希图循环
  • 添加了用于测试的 Actor 类

代码清单

import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;

public class ShortestPath {

    public static List<String> findShortestPath(Map<String, Actor> graph, String start,
        String end) {

        LinkedList<String> bfsList = new LinkedList<>();
        Queue<Actor> queue = new LinkedList<>();
        Map<String, Actor> prev = new HashMap<>();
        Actor current = graph.get(start);

        queue.add(current);
        current.setVisited(true);

        while (!queue.isEmpty()) {

            current = queue.remove();

            if (current.getName().equals(end)) {
                break;
            } else {
                LinkedList<Actor> currentFriends = current.getFriends();
                for (Actor currentFriend : currentFriends) {
                    if (!currentFriend.getVisited()) {
                        queue.add(currentFriend);
                        currentFriend.setVisited(true);
                        prev.put(currentFriend.getName(), current);
                    }
                }
            }
        }

        if (!current.getName().equals(end)) {
            System.out.println("\nThere is no path between " + start + " and " + end);
            return Collections.emptyList();
        }
        for (Actor node = graph.get(end); node != null; node = prev.get(node.getName())) {
            bfsList.add(node.getName());
        }
        Collections.reverse(bfsList);

        return bfsList;

    }

    static class Actor {

        private final String name;
        private final LinkedList<Actor> friends = new LinkedList<>();

        private boolean visited;

        Actor(String name) {
            this.name = name;
        }

        public void setVisited(boolean visited) {
            this.visited = visited;
        }

        // Would normally be `isVisited`
        public boolean getVisited() {
            return visited;
        }

        public String getName() {
            return name;
        }

        public LinkedList<Actor> getFriends() {
            return friends;
        }

        public void addFriend(Actor actor) {
            this.friends.add(actor);
        }
    }
}

测试代码

构建测试图并断言在各个节点之间找到正确的路径

import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;

public class ShortestPathTest {

    Map<String, ShortestPath.Actor> graph = new HashMap<>();

    @Before
    public void setup() {
        newActor("james", "harry", "luke", "john");
        newActor("harry", "luke", "mary");
        newActor("luke", "john", "hepzibah");
        newActor("john", "kate");
        newActor("mary", "hepzibah", "mia");
        newActor("hepzibah", "richard");
        newActor("kate", "martin", "mia");
        newActor("mia", "susan");
        newActor("richard", "rebecca");
        newActor("rebecca", "hannah");
        newActor("michelle");
    }

    private ShortestPath.Actor newActor(String name, String... friends) {
        ShortestPath.Actor actor = graph.computeIfAbsent(name, k -> new ShortestPath.Actor(name));
        for (String friendsName : friends) {
            ShortestPath.Actor friend = newActor(friendsName);
            actor.addFriend(friend);
            friend.addFriend(actor);
        }
        return actor;
    }

    @Test
    public void findShortestPath() {
        List<String> shortestPath = ShortestPath.findShortestPath(graph, "james", "mary");
        assertThat(shortestPath, equalTo(Arrays.asList("james", "harry", "mary")));
    }

    @Test
    public void findLongerShortestPath() {
        List<String> shortestPath = ShortestPath.findShortestPath(graph, "james", "mia");
        assertThat(shortestPath, equalTo(Arrays.asList("james", "harry", "mary", "mia")));
    }

    @Test
    public void findAnotherShortestPath() {
        List<String> shortestPath = ShortestPath.findShortestPath(graph, "harry", "hannah");
        assertThat(shortestPath, equalTo(Arrays.asList("harry", "luke", "hepzibah", "richard", "rebecca", "hannah")));
    }

    @Test
    public void findNoPath() {
        List<String> shortestPath = ShortestPath.findShortestPath(graph, "james", "michelle");
        assertThat(shortestPath, equalTo(Collections.emptyList()));
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-18
    相关资源
    最近更新 更多