Java algorithm DFS-find the shortest path of the maze exit
First set global variables
import java.util.Scanner;
public class DFS {
static int p,q,min=9999; //出口坐标(p,q),最小部署min
static int a[][] =new int [100][100];//1表示空地,2表示障碍
static int v[][] =new int [100][100];//0表示未访问,1表示一访问
static int dx[]= {
0,1,0,-1}; //x方向数组
static int dy[]= {
1,0,-1,0}; //y方向数组
static int maxx,maxy; //数组最大边界,作判定用
DFS Depth First Search
public static void dfs(int x,int y,int step) {
if(x==p && y==q) {
//如果到达,则比较step和min的值,获取最小的步数
if(step<min)
min=step;
return;
}
for(int i=0;i<4;i++) {
//循环四个方向
int tx=x+dx[i]; //按规律:右下左上
int ty=y+dy[i];
if(tx<=maxx && ty<=maxy) {
//判定是否越界
if(a[tx][ty]==1&&v[tx][ty]==0) {
//判定a是否有障碍,v是否走过
v[tx][ty]=1; //走过的v变成1
dfs(tx,ty,step+1); //递归入口
v[tx][ty]=0; //退出递归返回上一步,把v设为0
}
}
}
return;
}
Without the above loop, list the function codes in the four directions
//不用上面的循环的话,列出四个方向的函数
// if(a[x][y+1]==1 && v[x][y+1]==0) 右
// {
// v[x][y+1]=1;
// dfs(x,y+1,step+1);
// v[x][y+1]=0;
// }
// if(a[x+1][y]==1 && v[x+1][y]==0) 下
// {
// v[x+1][y]=1;
// dfs(x+1,y,step+1);
// v[x+1][y]=0;
// }
// if(a[x][y-1]==1 && v[x][y-1]==0) 左
// {
//
// v[x][y-1]=1;
// dfs(x,y-1,step+1);
// v[x][y-1]=0;
// }
// if(a[x-1][y]==1 && v[x-1][y]==0) 上
// {
//
// v[x-1][y]=1;
// dfs(x-1,y,step+1);
// v[x-1][y]=0;
// }
Main function settings
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
maxx = in.nextInt();
maxy = in.nextInt();
for(int i =1; i<=maxx;i++)
for(int j=1;j<=maxy;j++)
a[i][j]=in.nextInt();
int startx=in.nextInt(); //设置起始位置
int starty=in.nextInt(); //设置起始位置
p=in.nextInt(); //设置目标位置
q=in.nextInt(); //设置目标位置
v[startx][starty]=1;
dfs(startx,starty,0);
System.out.println("找到最短步数为:"+min);
}
}