您的位置:首页 > 其它

POJ 3083 Children of the Candy Corn

2014-10-02 11:06 429 查看
题意:给你一个图,告诉你起始点S,终点E,‘.’可走,‘#’不可走。求从起点到终点1.总是先选择向左走的步数。2.总是选择先向右走的步数。3.最短路

思路:

对于第一种和第二种,用深搜,只要写对存方向的数组即可:

int r[4][2]= {{0,-1},{1,0},{0,1},{-1,0}};
int l[4][2]= {{0,1},{1,0},{0,-1},{-1,0}};

对于第三种,广搜求最短路:具体见代码~~

#include<iostream>
#include<stdio.h>
#include<cstring>
#include<iomanip>
#include<queue>
#include<algorithm>
using namespace std;
struct node
{
int w;
int e;
int step;
};
int n,m;
int vist[50][50];
int r[4][2]= {{0,-1},{1,0},{0,1},{-1,0}};
int l[4][2]= {{0,1},{1,0},{0,-1},{-1,0}};
int dir[4][2]={{0,1},{-1,0},{1,0},{0,-1}};
char map[50][50];
int sx,sy,ex,ey,ans;
int dfs1(int x,int y,int step)
{
if(x==ex&&y==ey)
return step+1;
if(x<0||x>=n||y<0||y>=m||map[x][y]=='#')
return 0;
ans=(ans+3)%4;
int temp=0;
while(1)
{
temp=dfs1(x+l[ans][0],y+l[ans][1],step+1);
if(temp!=0)
break;
ans=(ans+1)%4;
}
return temp;
}
int dfs2(int x,int y,int step)
{
if(x==ex&&y==ey)
return step+1;
if(x<0||x>=n||y<0||y>=m||map[x][y]=='#')
return 0;
ans=(ans+3)%4;
int temp=0;
while(1)
{
temp=dfs2(x+r[ans][0],y+r[ans][1],step+1);
if(temp!=0)
break;
ans=(ans+1)%4;
}
return temp;
}
int bfs()
{
memset(vist,0,sizeof(vist));
int i,x,y;
struct node p;
queue<struct node>Q;
p.w=sx;
p.e=sy;
p.step=1;
Q.push(p);
vist[sx][sy]=1;
while(!Q.empty())
{
p=Q.front();
Q.pop();
if(p.w==ex&&p.e==ey)
return p.step;
for(i=0;i<4;i++)
{
x=p.w+dir[i][0];
y=p.e+dir[i][1];
if(x>=0&&x<n&&y>=0&&y<m&&map[x][y]!='#'&&vist[x][y]==0)
{
vist[x][y]=1;
struct node t;
t.w=x;
t.e=y;
t.step=p.step+1;
Q.push(t);
}
}
}
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&m,&n);
getchar();
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
{
scanf("%c",&map[i][j]);
if(map[i][j]=='S')
{
sx=i;
sy=j;
}
if(map[i][j]=='E')
{
ex=i;
ey=j;
}
}
getchar();
}
ans=0;
printf("%d ",dfs1(sx,sy,0));
ans=0;
printf("%d ",dfs2(sx,sy,0));
printf("%d\n",bfs());
}
return 0;
}


好好训练不做弱菜~~!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: