标签:
这有一个迷宫,有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
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 }
标签:
原文地址:http://www.cnblogs.com/a1225234/p/4637550.html