import java.io.PrintStream;
public class Path {
static PrintStream out=System.out;
static boolean pathfound=false;
public static void main(String $[]){
boolean arr[][]=new boolean[5][5];
for(int i=0;i<arr.length;i++)
for(int j=0;j<arr[0].length;j++) {
if (i==j)
arr[i][j] = true;
}
travel(arr,0,0,arr.length-1,arr[0].length-1);
if(pathfound)
out.println("Path is found");
else
out.println("Path is not found");
}
static boolean travel(boolean a[][],int r,int c,int targetR,int targetC){
if(r==targetR && c==targetC){
pathfound=true;
}
if(!pathfound && r+1<a.length)
if(a[r+1][c]){
a[r+1][c]=false;
pathfound=travel(a,r+1,c,targetR,targetC);
}
if(!pathfound && r-1>=0)
if(a[r-1][c]){
a[r-1][c]=false;
pathfound=travel(a,r-1,c,targetR,targetC);
}
if(!pathfound && c+1<a[0].length)
if(a[r][c+1]){
a[r][c+1]=false;
pathfound=travel(a,r,c+1,targetR,targetC);
}
if(!pathfound && c-1>=0)
if(a[r][c-1]){
a[r][c-1]=false;
pathfound=travel(a,r,c-1,targetR,targetC);
}
if(!pathfound && c-1>=0 && r-1>=0)
if(a[r-1][c-1]){
a[r-1][c-1]=false;
pathfound=travel(a,r-1,c-1,targetR,targetC);
}
if(!pathfound && c+1<a[0].length && r-1>=0)
if(a[r-1][c+1]){
a[r-1][c+1]=false;
pathfound=travel(a,r-1,c+1,targetR,targetC);
}
if(!pathfound && c+1<a[0].length && r+1<a.length)
if(a[r+1][c+1]){
a[r+1][c+1]=false;
pathfound=travel(a,r+1,c+1,targetR,targetC);
}
if(!pathfound && c-1>=0 && r+1<a.length)
if(a[r+1][c-1]){
a[r+1][c-1]=false;
pathfound=travel(a,r+1,c-1,targetR,targetC);
}
if(pathfound)
out.println(r+" "+c);
return pathfound;
}
}
如果路径存在,上述代码将找到起始单元格和目标单元格之间的路径。
它生成的输出:
4 4
3 3
2 2
1 1
0 0
Path is found
A*
,它是Dijkstra's Algorithm
的变体。https://www.baeldung.com/java-a-star-pathfinding - Aman