[英]In a Grid(nxn), how to find k,k+1,k+2 paths from one point to another point?
Consider the grid (a matrix with n=3): 考虑网格(n = 3的矩阵):
0 1 2
3 4 5
6 7 8
I need to find k+1
, k+2
paths between any point to any point (here from 3 to 2),where k
is the shortest distance or number of hops ( k=3
). 我需要找到任意点到任意点(此处为3到2)之间的
k+1
, k+2
条路径,其中k
是最短距离或跳数( k=3
)。 How do I go about find paths of dist k=4
or k=5
? 如何查找dist
k=4
或k=5
路径?
I have a program (in java) for finding all the k
paths : 我有一个用于查找所有
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;
}
By using the distance formula, I am able to restrict the number of vertical and horizontal movements and use recursion to find all the points in the shortest path. 通过使用距离公式,我可以限制垂直和水平移动的数量,并可以使用递归找到最短路径中的所有点。 Can someone please suggest something similar for paths with a dist >3?
有人可以为dist> 3的路径建议类似的东西吗?
Ignore the fact that it is a grid. 忽略它是网格的事实。 Just consider it as a graph.
只需将其视为图形即可。 You have points.
你有分数。 Each point has neighbors.
每个点都有邻居。 Each point has a minimum distance to the final point.
每个点到终点都有一个最小距离。 Here is some Python to demonstrate an algorithm.
这是一些Python来演示算法。 (Translation to Java should not be hard.)
(翻译成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
As a significant optimization you may note that in your case all paths from p1
to p2
have the same length mod 2. Therefore for length k + i
there are no paths at all unless i
is even. 作为一项重要的优化,您可能会注意到,从
p1
到p2
所有路径都具有相同的长度模2。因此,对于长度k + i
,除非i
是偶数,否则根本没有路径。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.