Consider the grid (a matrix with 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
). How do I go about find paths of dist k=4
or k=5
?
I have a program (in java) for finding all the k
paths :
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?