poj 3083 DFS
生活随笔
收集整理的這篇文章主要介紹了
poj 3083 DFS
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?? poj3083
?? ?用DFS和BFS。通過這題,我對DFS和BFS再次有了初步的認識!!但是方向問題真的好繞啊。。真心沒搞懂,還是看了別人的才做出來的。下來我計劃再做幾道DFS和BFS的題。然后,再去獨立把上學期數據結構書上的迷宮那題給搞出來,用兩種方法,這也許就我暫時的目的吧。
? 再接再勵。
#include <iostream>#include <cstdio>
#include <queue>
#include <fstream>
#include <memory.h>
#define MAX 45
using namespace std;
struct node{
int x,y;
int step;
};
int flag[MAX][MAX];
char map[MAX][MAX];
int dir1[4][2]={{0,-1},{1,0},{0,1},{-1,0}}; // Left first
int dir2[4][2]={{0,1},{1,0},{0,-1},{-1,0}}; //Right first
int w,h;
int d1,d2;
int start[2],end[2];
void getmap(){
memset(flag,0,sizeof(flag));
for(int i=0; i<h; i++)
{
cin>>map[i];
for(int j=0; j<w; j++)
{
if(map[i][j]=='#')
flag[i][j]=1;
else if(map[i][j]=='S')
{
start[0]=i;
start[1]=j;
flag[i][j]=1;
}
else if(map[i][j]=='E')
{
end[0]=i;
end[1]=j;
}
}
}
if(start[0]==0)
{ // S on the down-side
d1=1;
d2=1;
}
else if(start[0]==h-1)
{ //upside
d1=3;
d2=3;
}
else if(start[1]==w-1)
{ //right side
d1=2;
d2=0;
}
else
{ //left side
d1=0;
d2=2;
}
}
int dfs(int x,int y,int d,int dir[][2])
{
int step,sx,sy,temp;
if(x==end[0] && y==end[1])
return 1;
for(int i=0; i<4; i++)
{
temp=(d+i)%4;
sx=x+dir[temp][1];
sy=y+dir[temp][0];
if(sx>=0 && sx<h && sy>=0 && sy<w && flag[sx][sy]==0)
break;
}
step=dfs(sx,sy,(temp+3)%4,dir)+1;
return step;
}
int bfs(){
queue<node> q;
node p;
p.x=start[0];
p.y=start[1];
p.step=1;
q.push(p);
while(!q.empty())
{
p=q.front();
q.pop();
if(p.x==end[0] && p.y==end[1]) //End
return p.step;
for(int i=0; i<4; i++){
node temp;
temp.x=p.x+dir1[i][1];
temp.y=p.y+dir1[i][0];
if(temp.x>=0 && temp.x<h && temp.y>=0 && temp.y<w
&& !flag[temp.x][temp.y]){
flag[temp.x][temp.y]=1;
temp.step=p.step+1;
q.push(temp);
}
}
}
return 0;
}
int main()
{
int n;
freopen("acm.txt","r",stdin);
scanf("%d",&n);
while(n--){
scanf("%d%d",&w,&h);
getmap();
printf("%d ",dfs(start[0],start[1],d1,dir1)); //Left
printf("%d ",dfs(start[0],start[1],d2,dir2)); //Right
printf("%d\n",bfs());
}
return 0;
}
?
轉載于:https://www.cnblogs.com/Jason-Damon/archive/2012/03/11/2390703.html
總結
以上是生活随笔為你收集整理的poj 3083 DFS的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: WordPress 短代码集
- 下一篇: 动态规划--凸多边形最优三角剖分