繁体   English   中英

在Grid(nxn)中,如何找到从一个点到另一点的k,k + 1,k + 2条路径?

[英]In a Grid(nxn), how to find k,k+1,k+2 paths from one point to another point?

考虑网格(n = 3的矩阵):

0 1 2
3 4 5
6 7 8

我需要找到任意点到任意点(此处为3到2)之间的k+1k+2条路径,其中k是最短距离或跳数( k=3 )。 如何查找dist k=4k=5路径?

我有一个用于查找所有k路径的程序(在Java中):

public ArrayList<Path> findPath(int y1, int x1, int y2, int x2){

       int vert = y1-y2;//1
       int hori = x1-x2;//-2
       int max = (vert > 0 ? vert : -vert)+(hori > 0 ? hori : -hori);

       return findPath(y1,x1,vert,hori,vert,hori,0,max);
    }

    public ArrayList<Path> findPath(int y, int x, int vert, int hori, int v, int h, int level, int max){
       if(level > max){
           System.exit(1);
       }
       System.out.println(y+","+x+","+vert+","+hori+","+v+","+h);
       ArrayList<Path> ret = new ArrayList<Path>();
       if(v == 0 && h == 0){
           ret.add(new Path());
           ret.get(0).pushPath(network[y][x]);
           return ret;
       }

       int vm = vert > 0 ? -1 : 1;//-1
       int hm = hori > 0 ? -1 : 1;//1
       System.out.println(vm+","+hm);

       ArrayList<Path> a = new ArrayList<Path>();
       if(v!=0){ a = findPath(y+vm, x, vert, hori, v+vm, h, level+1, max); }

       ArrayList<Path> b = new ArrayList<Path>();
       if(h!=0){ b = findPath(y, x+hm, vert, hori, v, h+hm, level+1, max); }

       for(Path p : a){
           p.pushPath(network[y][x]);
          }

       for(Path p : b){
           p.pushPath(network[y][x]);
       }

       ret = new ArrayList<Path>(a);
       ret.addAll(b);
       return ret;  

     }

通过使用距离公式,我可以限制垂直和水平移动的数量,并可以使用递归找到最短路径中的所有点。 有人可以为dist> 3的路径建议类似的东西吗?

您可能会看到Johnson算法(第一部分第二部分) ,该算法在有向图中枚举了所有基本电路(循环)。

忽略它是网格的事实。 只需将其视为图形即可。 你有分数。 每个点都有邻居。 每个点到终点都有一个最小距离。 这是一些Python来演示算法。 (翻译成Java应该不难。)

def paths(p1, p2, length):
    answer = []
    if 0 == length and p1 == p2:
        answer = [p1]
    elif length <= distance(p1, p2):
        for p in neighbors(p1):
            answer.extend([ [p1] + x for x in paths(p, p2, length-1) ])
    return answer

作为一项重要的优化,您可能会注意到,从p1p2所有路径都具有相同的长度模2。因此,对于长度k + i ,除非i是偶数,否则根本没有路径。

暂无
暂无

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

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