最少步数(dfs + bfs +bfs优化)
生活随笔
收集整理的這篇文章主要介紹了
最少步数(dfs + bfs +bfs优化)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
?
最少步數
時間限制: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表示墻。
現(xiàn)在輸入一個道路的坐標作為起點,再如輸入一個道路的坐標作為終點,問最少走幾步才能從起點到達終點?
(注:一步是指從一坐標點走到其上下左右相鄰坐標點,如:從(3,1)到(4,1)。)
隨后n行,每行有四個整數a,b,c,d(0<=a,b,c,d<=8)分別表示起點的行、列,終點的行、列。
?廣搜:
1 #include<stdio.h> 2 #include<queue> 3 #include<string.h> 4 using namespace std; 5 const int INF=0xfffffff; 6 int disx[4]={0,1,-1,0}; 7 int disy[4]={1,0,0,-1}; 8 struct Node{ 9 int nx,ny,step; 10 }; 11 queue<Node>dl; 12 Node a,b; 13 int x,y,ex,ey,T,mi; 14 int map[10][10]; 15 void bfs(){ 16 map[x][y]=1; 17 a.nx=x;a.ny=y;a.step=0; 18 dl.push(a); 19 while(!dl.empty()){ 20 a=dl.front(); 21 dl.pop(); 22 map[a.nx][a.ny]=1; 23 if(a.nx==ex&&a.ny==ey){ 24 if(a.step<mi)mi=a.step; 25 map[ex][ey]=0; 26 } 27 for(int i=0;i<4;i++){ 28 b.nx=a.nx+disx[i];b.ny=a.ny+disy[i];b.step=a.step+1; 29 if(!map[b.nx][b.ny]&&b.step<=mi&&b.nx>=0&&b.ny>=0&&a.nx<9&&b.ny<9)dl.push(b); 30 } 31 } 32 } 33 int main(){ 34 scanf("%d",&T); 35 while(T--){int m[10][10]={ 36 {1,1,1,1,1,1,1,1,1}, 37 {1,0,0,1,0,0,1,0,1}, 38 {1,0,0,1,1,0,0,0,1}, 39 {1,0,1,0,1,1,0,1,1}, 40 {1,0,0,0,0,1,0,0,1}, 41 {1,1,0,1,0,1,0,0,1}, 42 {1,1,0,1,0,1,0,0,1}, 43 {1,1,0,1,0,0,0,0,1}, 44 {1,1,1,1,1,1,1,1,1} 45 }; 46 memcpy((int *)map,(int *)m,sizeof(m[0][0])*100); 47 scanf("%d%d%d%d",&x,&y,&ex,&ey); 48 mi=INF; 49 bfs(); 50 printf("%d\n",mi); 51 } 52 return 0; 53 } 1 #include<stdio.h> 2 #include<queue> 3 #include<string.h> 4 using namespace std; 5 const int INF=0xfffffff; 6 int disx[4]={0,1,-1,0}; 7 int disy[4]={1,0,0,-1}; 8 struct Node{ 9 int nx,ny,step; 10 friend bool operator < (Node a,Node b){ 11 return a.step > b.step; 12 } 13 }; 14 priority_queue<Node>dl; 15 Node a,b; 16 int x,y,ex,ey,T,mi; 17 int map[10][10]; 18 void bfs(){ 19 map[x][y]=1; 20 a.nx=x;a.ny=y;a.step=0; 21 dl.push(a); 22 while(!dl.empty()){ 23 a=dl.top(); 24 dl.pop(); 25 map[a.nx][a.ny]=1; 26 if(a.nx==ex&&a.ny==ey){ 27 if(a.step<mi)mi=a.step; 28 map[ex][ey]=0; 29 } 30 for(int i=0;i<4;i++){ 31 b.nx=a.nx+disx[i];b.ny=a.ny+disy[i];b.step=a.step+1; 32 if(!map[b.nx][b.ny]&&b.step<=mi&&b.nx>=0&&b.ny>=0&&a.nx<9&&b.ny<9)dl.push(b); 33 } 34 } 35 } 36 int main(){ 37 scanf("%d",&T); 38 while(T--){int m[10][10]={ 39 {1,1,1,1,1,1,1,1,1}, 40 {1,0,0,1,0,0,1,0,1}, 41 {1,0,0,1,1,0,0,0,1}, 42 {1,0,1,0,1,1,0,1,1}, 43 {1,0,0,0,0,1,0,0,1}, 44 {1,1,0,1,0,1,0,0,1}, 45 {1,1,0,1,0,1,0,0,1}, 46 {1,1,0,1,0,0,0,0,1}, 47 {1,1,1,1,1,1,1,1,1} 48 }; 49 memcpy((int *)map,(int *)m,sizeof(m[0][0])*100); 50 scanf("%d%d%d%d",&x,&y,&ex,&ey); 51 mi=INF; 52 bfs(); 53 printf("%d\n",mi); 54 } 55 return 0; 56 }?
轉載于:https://www.cnblogs.com/handsomecui/p/4702428.html
總結
以上是生活随笔為你收集整理的最少步数(dfs + bfs +bfs优化)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2015读书目录
- 下一篇: innodb和myisam数据类型,即在