啊哈算法第四章第二节解救小哈Java实现

时间:2023-03-08 20:00:37
啊哈算法第四章第二节解救小哈Java实现
package corejava;

public class FourTwo {
static int m;//(m,n)为几行几列
static int n;
static int p;//(p,q)为终点
static int q;
static int min=9999;
static int [][]a=new int [51][51];//存放地图
static int [][]b=new int [51][51];//存放路径
static String []record=new String[9999]; public static void dfs(int x,int y,int step)
{
int [][]next={{0,1},{1,0},{0,-1},{-1,0}};
if(x==p&y==q)
{
System.out.println("step"+step);
for(int i=0;i<step;i++)
{
System.out.print(record[i]);
}
System.out.println(" "); if(step<min)
{
min=step; }
return; }
for(int k=0;k<4;k++)
{
int tx=x+next[k][0];
int ty=y+next[k][1];
if(tx<0||tx>=m||ty<0||ty>=n)
{
continue; }
if(a[tx][ty]==0&b[tx][ty]==0)
{ record[step]="("+tx+","+ty+")"; b[tx][ty]=1;
dfs(tx,ty,step+1);//若这行代码变为step++;dfs(tx,ty,step);则改变了for循环里step的值,就会出问题
b[tx][ty]=0;
} }
return;
}
public static void main(String []args)
{ m = 5;
n = 4;
int startx=0;
int starty=0;
p=3;
q=2;
b[startx][starty]=1;
record[0]="("+0+","+0+")";
a[0][2]=1;
a[2][2]=1;
a[3][1]=1;
a[4][3]=1; dfs(startx,starty,0);
System.out.println("min"+min); } }

这里感觉获取输入太麻烦,直接设置了固定值。同时dfs(tx,ty,step+1);这里很困扰我,开始没有考虑step在循环中用到,step=step+1后改变了循环里step的值,查询了好久才知道出错的原因。