您的位置:首页 > 其它

POJ 3083 Children of the Candy Corn(BFS+DFS)

2016-04-21 12:56 330 查看
题目:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=105916#problem/H

代码:

#include<stdio.h>
#include<string.h>
#include<queue>

using namespace std;
char maps[45][45];
int book[45][45];
int fx[4]= {1,0,-1,0};
int fy[4]= {0,1,0,-1};
int n,m;
int startx,starty;
struct node
{
int x,y;
int step;
} ui,op;
int step;
int dl[][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
int dr[][2] = {{0, 1}, {-1, 0}, {0, -1}, {1, 0}};

int dfs(int x, int y, int d, int step, int dir[][2])
{
for(int i=0; i<4; i++)
{
int j = ((d-1+4)%4+i)%4;
int nx = x+dir[j][0];
int ny = y+dir[j][1];

if(maps[nx][ny]=='E') return step+1;
if(nx < 0 || ny < 0 || nx>m || ny>n) continue;
if(maps[nx][ny] == '#') continue;
//printf("%d %d\n",nx,ny);
return dfs(nx, ny, j, step+1, dir);
}
}

void bfs(int x,int y)
{
memset(book,0,sizeof(book));
ui.x=x;
ui.y=y;
ui.step=1;
queue<node>q;
book[x][y]=1;
q.push(ui);

while(!q.empty())
{
ui=q.front();
q.pop();

if(maps[ui.x][ui.y]=='E')
{
printf("%d\n",ui.step);
return;
}

for(int i=0; i<4; i++)
{
op.x=ui.x+fx[i];
op.y=ui.y+fy[i];

if(op.x>=0&&op.x<m&&op.y>=0&&op.y<n)
{
if(maps[op.x][op.y]!='#')
{
if(book[op.x][op.y]==0)
{
op.step=ui.step+1;
book[op.x][op.y]=1;
q.push(op);
}
}
}
}
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
memset(maps,0,sizeof(maps));

for(int i=0; i<m; i++)
{
scanf("%s",&maps[i]);
for(int j=0; j<n; j++)
{
if(maps[i][j]=='S')
{
startx=i;
starty=j;
}
}
}
//printf("%d %d\n",startx,starty);
int d1,d2;
if(startx == 0)
{
d1 = 3;
d2 = 3;
}
else if(startx == m-1)
{
d1 = 1;
d2 = 1;
}
else if(starty == 0)
{
d1 = 2;
d2 = 0;
}
else if(starty == n-1)
{
d1 = 0;
d2 = 2;
}
step=0;
printf("%d ", dfs(startx, starty, d1, 1, dl));
//printf("\n1\n");
//printf("%d %d\n",startx,starty);
step=0;
printf("%d ", dfs(startx, starty, d2, 1, dr));
bfs(startx,starty);
//getchar();
}
}


深搜的代码是照网上抄的。
太难了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: