The Game
Description
Input
Output
Sample Input
5 4 XXXXX X X XXX X XXX 2 3 5 3 1 3 4 4 2 3 3 4 0 0 0 0 0 0
Sample Output
Board #1: Pair 1: 4 segments. Pair 2: 3 segments. Pair 3: impossible.
题目大意:类似于一个连连看游戏吧。求最小线段数。如例图,线段数,一个4,一个3。
思路:我想那种求图,两点最小步数的题,大家都做过。但是,这个怎么办了。只有加一个 dire记录方向即可。如果,next.dire!=cur.dire.则线段数+1.
代码如下:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<cctype>
#include<queue>
#include<stack>
#define INF 0x3f3f3f3f
#define maxn 100001
using namespace std;
int n,m;
char map[80][80];
int go[4][2]={{-1,0},{0,1},{1,0},{0,-1}};// 0 1 2 3
int vis[80][80];
int sx,sy,ex,ey;
struct node{
int x,y;
int seg;
int dire;
node(){}
node(int a,int b,int c,int d)
{
x=a;
y=b;
seg=c;
dire=d;
}
};
int bfs()
{
queue<node> que;
que.push(node(sx,sy,0,-1));
memset(vis,0,sizeof vis);
vis[sx][sy]=1;
while(!que.empty())
{
node cur=que.front();
node next;
que.pop();
for(int i=0;i<4;i++)
{
next.x=cur.x+go[i][0];
next.y=cur.y+go[i][1];
next.dire=i;
if(next.x>=0&&next.x<=n+1&&next.y>=0&&next.y<=m+1&&!vis[next.x][next.y])
{
if(next.dire==cur.dire)
next.seg=cur.seg;
else
next.seg=cur.seg+1;
if(next.x==ex&&next.y==ey)
return next.seg;
if(map[next.y][next.x]!='X')
{
//cout<<next.x<<next.y<<next.seg<<endl;
vis[next.x][next.y]=1;
que.push(next);
}
}
}
}
return 0;
}
int main()
{
int t=0;
while(scanf("%d%d",&n,&m),n||m)
{
t++;
int cas=0;
memset(map,' ',sizeof map);
for(int i=1;i<=m;i++)
{
getchar();
for(int j=1;j<=n;j++)
scanf("%c",&map[i][j]);
}
//cout<<"15"<<map[4][2]<<endl;
printf("Board #%d:\n",t);
while(1)
{
//cout<<"---->\n";
scanf("%d%d%d%d",&sx,&sy,&ex,&ey);
//cout<<sx<<sy<<ex<<ey<<endl;
if(sx||sy||ex||ey)
{
int temp=bfs();
//cout<<"--------->>>>>>>>\n";
if(temp)
printf("Pair %d: %d segments.\n",++cas,temp);
else
printf("Pair %d: impossible.\n",++cas);
}
else
break;
}
printf("\n");
}
return 0;
}
POJ 1101 The Game(BFS+判方向),布布扣,bubuko.com
原文:http://blog.csdn.net/code_or_code/article/details/36891741