这有一个迷宫,有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
AC-code:
#include<cstdio> #include<cstring> #define INF 0xfffffff int x,y,ex,ey,min,c; int dx[4]={1,0,-1,0}; int dy[4]={0,1,0,-1}; int map[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, }; void dfs(int x,int y,int c) { int i; if(x==ex&&y==ey) { if(c<min) min=c; return ; } for(i=0;i<4;i++) { int nx=x+dx[i]; int ny=y+dy[i]; if(map[nx][ny]==0&&c+1<min) { map[nx][ny]=1; dfs(nx,ny,c+1); map[nx][ny]=0; } } } int main() { int n; scanf("%d",&n); while(n--) { int c; scanf("%d%d%d%d",&x,&y,&ex,&ey); map[x][y]=1; c=0;min=INF; dfs(x,y,c); map[x][y]=0; printf("%d\n",min); } }