简体   繁体   English

BFS使用2个队列查找二维矩阵的最短路径

[英]BFS Find Shortest Path of 2d matrix using 2 queues

What I'm trying to do: 我正在尝试做的是:

Using a graph found in a text file, find and print the shortest path (minimum amount of vertices) from vertex A to vertex B. 使用在文本文件中找到的图形,找到并打印从顶点A到顶点B的最短路径(最小数量的顶点)。

Current implementation: 当前实施:

public String findPath(int v, int w) {
    Queue<Integer> q = new LinkedList<Integer>();
    boolean[] visited = new boolean[g.numVertices()];
    String[] pathTo = new String[g.numVertices()];

    q.add(v);
    pathTo[v] = v+" ";
    while(q.peek() != null) {
        if(runBFS(q.poll(),w,visited,q,pathTo))
        break;
    }
    return pathTo[w];
}

private boolean runBFS(int v, int w, boolean[] visited, Queue<Integer> q, String[] pathTo) {
    if(visited[v]) {
    }
    else if(v == w)
        return true; 
    }
    else {
        visited[v] = true;
        VertexIterator vi = g.adjacentVertices(v);
        while(vi.hasNext()) {
            int nextVertex = vi.next();
            pathTo[nextVertex] = pathTo[v] + nextVertex + " ";
            q.add(nextVertex);
        }
    }
    return false;
}

v = vertex of origin v =原点

w = target vertex w =目标顶点

g = graph g =图

vi = a normal iterator that iterates over the neighbours of v vi =在v的邻居上进行迭代的普通迭代器

Right now , it is using String[] to trace the paths but I was suggested that there is a solution to do this with Queue<ArrayList<Integer>> rather than String[] when saving paths by running this queue in parallel with the q queue. 现在,它使用String []来跟踪路径,但是建议我有一种解决方案,当通过与q并行运行此队列来保存路径时,可以使用Queue<ArrayList<Integer>>而不是String[]来实现。队列。

Could someone guide me through this ? 有人可以指导我做这个吗?

You can use a second queue Queue<ArrayList<Integer>> q2 to store the shortest path (as an ArrayList<Integer> ) from v to each node currently in q in the same order. 您可以使用第二个队列Queue<ArrayList<Integer>> q2以相同的顺序存储从v到当前q中每个节点的最短路径(作为ArrayList<Integer> )。 Whenever you poll q , you also poll q2 , and whenever you add a node to q , you calculate the shortest path to that node by copying the shortest path to the previous node and appending the current node, and add it to q2 . 每当轮询q ,也会轮询q2 ,并且每当将一个节点添加到q ,您都可以通过将最短路径复制到前一个节点并追加当前节点并将其添加到q2来计算该节点的最短路径。

Note, however, that copying the shortest path may take time linear in the number of vertices, which will increase the overall complexity. 但是请注意,复制最短路径可能会花费时间,而时间在顶点数量上是线性的,这会增加整体复杂度。 For this reason I wouldn't recommend this approach. 因此,我不推荐这种方法。 Instead, for each node n you can store the previous node you came from when you visited n. 相反,对于每个节点n,您可以存储访问n时来自的前一个节点。 As soon as you reach the target node w, you can then backtrack through these previous nodes to find the shortest path from the start node. 一旦到达目标节点w,您就可以回溯这些先前的节点,以找到距起始节点最短的路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM