题目链接:点击打开链接
这有一个迷宫,有0~8行和0~8列:
1,1,1,1,1,1,1,1,1
1,0,0,1,0,0,1,0,1
1,0,0,1,1,0,0,0,1
1,0,1,0,1,1,0,1,1
1,0,0,0,0,1,0,0,1
1,1,0,1,0,1,0,0,1
1,1,0,1,0,1,0,0,1
1,1,0,1,0,0,0,0,1
1,1,1,1,1,1,1,1,1
0表示道路,1表示墙。
现在输入一个道路的坐标作为起点,再如输入一个道路的坐标作为终点,问最少走几步才能从起点到达终点?
(注:一步是指从一坐标点走到其上下左右相邻坐标点,如:从(3,1)到(4,1)。)
2 3 1 5 7 3 1 6 7
12 11
dfs:
#include
#include
int a[10][10]= {{1,1,1,1,1,1,1,1,1},{1,0,0,1,0,0,1,0,1},{1,0,0,1,1,0,0,0,1},{1,0,1,0,1,1,0,1,1},{1,0,0,0,0,1,0,0,1},{1,1,0,1,0,1,0,0,1},{1,1,0,1,0,1,0,0,1},{1,1,0,1,0,0,0,0,1},{1,1,1,1,1,1,1,1,1}};
int m,n,p,q,step,ans,vis[10][10];
void dfs(int x,int y,int z)
{
int next[4][2]= {{0,1},{1,0},{0,-1},{-1,0}};
if(x==p&&y==q)
{
if(z9||ty<0||ty>9)
continue;
if(a[tx][ty]==0&&vis[tx][ty]==0)
{
vis[tx][ty]=1;
dfs(tx,ty,z+1);
vis[tx][ty]=0;
}
}
return;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
ans=999999;
memset(vis,0,sizeof(vis));
scanf("%d%d%d%d",&m,&n,&p,&q);
vis[m][n]=1;
dfs(m,n,0);
printf("%d\n",ans);
}
}
bfs:
#include
#include
int vis[10][10],m,n,p,q,tx,ty,ans,tail,head;
int a[9][9]=
{
1,1,1,1,1,1,1,1,1,
1,0,0,1,0,0,1,0,1,
1,0,0,1,1,0,0,0,1,
1,0,1,0,1,1,0,1,1,
1,0,0,0,0,1,0,0,1,
1,1,0,1,0,1,0,0,1,
1,1,0,1,0,1,0,0,1,
1,1,0,1,0,0,0,0,1,
1,1,1,1,1,1,1,1,1
};
struct node
{
int x,y,s;
} que[100];
int main()
{
int t,next[4][2]= {{0,1},{1,0},{0,-1},{-1,0}};
scanf("%d",&t);
while(t--)
{
int flag=0;
head=tail=0;
memset(vis,0,sizeof(vis));
scanf("%d%d%d%d",&m,&n,&p,&q);
que[tail].x=m,que[tail].y=n,que[tail].s=0;
tail++;
vis[m][n]=1;
if(m==p&&n==q)//特判
printf("0\n");
else
{
while(head8||ty<0||ty>8)
continue;
if(a[tx][ty]==0&&vis[tx][ty]==0)
{
vis[tx][ty]=1;
que[tail].x=tx;
que[tail].y=ty;
que[tail].s=que[head].s+1;
tail++;
}
if(tx==p&&ty==q)
{
flag=1;
break;
}
}
if(flag)
break;
head++;
}
printf("%d\n",que[tail-1].s);
}
}
}