最少步数(bfs)

最少步数

时间限制:3000 ms  |  内存限制:65535 KB
难度:4
 
描述

这有一个迷宫,有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)。)

 
输入
第一行输入一个整数n(0<n<=100),表示有n组测试数据;
随后n行,每行有四个整数a,b,c,d(0<=a,b,c,d<=8)分别表示起点的行、列,终点的行、列。
输出
输出最少走几步。
样例输入
2
3 1  5 7
3 1  6 7
样例输出
12
11
TLE code
 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cstdio>
 4 #include <cstring>
 5 using namespace std;
 6 int a,b,c,t;
 7 int map[51][51][51];
 8 int Min=100000;
 9 int dirx[4]={0,0,1,-1},diry[4]={1,-1,0,0},dirz[2]={1,-1};
10 int dfs(int z,int x,int y,int step)
11 {
12     int i,j;
13     if(step>t||z<0||z>=a||x<0||x>=b||y<0||y>=c)
14         return 0;
15     if(map[z][x][y])
16         return 0;
17     if(x==b-1&&y==c-1&&z==a-1)
18     {
19         Min=min(Min,step);
20         return 0;
21     }
22     else
23     {
24         step++;
25         map[z][x][y]=1;
26         for(i=0;i<4;i++)
27         {
28             int xx=x+dirx[i],yy=y+diry[i];
29             dfs(z,xx,yy,step);
30         }
31         for(i=0;i<2;i++)
32         {
33             int zz=z+dirz[i];
34             dfs(zz,x,y,step);
35         }
36         map[z][x][y]=0;
37     }
38     return 0;
39 }
40 int main()
41 {
42     int k,i,j,p;
43     //freopen("in.txt","r",stdin);
44     cin>>k;
45     while(k--)
46     {
47         Min=1000000;
48         cin>>a>>b>>c>>t;
49         for(i=0;i<a;i++)        //
50             for(j=0;j<b;j++)
51                 for(p=0;p<c;p++)
52                     cin>>map[i][j][p];
53         dfs(0,0,0,0);
54         if(Min>t)
55             cout<<-1<<endl;
56         else
57             cout<<Min<<endl;
58     }
59 }

AC code

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <algorithm>
 4 using namespace std;
 5 int a,b,c,d,m;
 6 int x[9][9]={
 7      1,1,1,1,1,1,1,1,1,
 8      1,0,0,1,0,0,1,0,1,
 9      1,0,0,1,1,0,0,0,1,
10      1,0,1,0,1,1,0,1,1,
11      1,0,0,0,0,1,0,0,1,
12      1,1,0,1,0,1,0,0,1,
13      1,1,0,1,0,1,0,0,1,
14      1,1,0,1,0,0,0,0,1,
15      1,1,1,1,1,1,1,1,1,
16 };
17 int bfs(int p,int q,int s)
18 {
19     if(x[p][q]==1)
20         return 0;
21     if(p==c&&q==d)
22     {
23         m=min(s,m);
24         return 0;
25     }
26     s++;
27     x[p][q]=1;//不再返回
28     bfs(p-1,q,s);//向四周搜索
29     bfs(p+1,q,s);
30     bfs(p,q+1,s);
31     bfs(p,q-1,s);
32     x[p][q]=0;//不得返回。。。看了半天才明白
33     return 0;
34 }
35 int main()
36 {
37     int N;
38     cin>>N;
39     while(N--)
40     {
41         cin>>a>>b>>c>>d;
42         m=100000;
43         bfs(a,b,0);
44         cout<<m<<endl;
45     }
46     return 0;
47 }
原文地址:https://www.cnblogs.com/a1225234/p/4637550.html