POJ_1101 The Game ( BFS )

  /*从昨天下午看这道题,一直到现在,以前做过一个类似连连看的题,跟这题差不多,
就按那个思路写了,一步一步的搜,我晕,把bfs写暴也没能AC。上午请教牛人,说bfs时
不要搜步数,直接搜直线数。就是一条路走到头,不撞南墙不死心(大体是这个意思
^_^)。然后就是正常的bfs写法。入队列,出队列。。。

  ps:注意标点符号T_T.
*/

//My Code:

#include <iostream>
#include <cstring>
#include <cstdio>

using namespace std;

const int N = 80;

struct node{
int x;
int y;
int time;
}q[N*N];

int dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
char map[N][N];
bool vis[N][N];
int w, h;
int sx, sy, ex, ey;

int bfs(){
int f = 0, r = 0, x, y;
int tx, ty, ti, i;

q[r].x = sx; q[r].y = sy; q[r].time = 0; r++;

while(f < r){
x = q[f].x; y = q[f].y; ti = q[f].time; ti++; f++;
for(i = 0; i < 4; i++){
tx = x + dir[i][0];
ty = y + dir[i][1];

if(tx < 0 || tx > h+1 || ty < 0 || ty > w+1)
continue;
while(1){
if(tx == ex && ty == ey)
return ti;
if(map[tx][ty] == 'X' || tx < 0 || tx > h+1 || ty < 0 || ty > w+1)
break;
if(!vis[tx][ty]){
vis[tx][ty] = true;
q[r].x = tx;
q[r].y = ty;
q[r].time = ti;
r++;
}
tx += dir[i][0]; ty += dir[i][1];
}
}
}
return -1;
}

int main(){
//freopen("data.in", "r", stdin);

int i, j, ans, board = 0, pair;
while(~scanf("%d%d", &w, &h)){
if(!w && !h) break;

getchar(); pair = 0;
memset(map, 0, sizeof(map));

printf("Board #%d:\n", ++board);

for(i = 1; i <= h; i++){
for(j = 1; j <= w; j++)
scanf("%c", &map[i][j]);
getchar();
}

while(~scanf("%d%d%d%d", &sy, &sx, &ey, &ex)){
if(!sx && !sy && !ex && !ey) break;

memset(vis, 0, sizeof(vis));
ans = bfs();

printf("Pair %d: ", ++pair);

if(ans == -1) puts("impossible.");
else printf("%d segments.\n", ans);
}
putchar('\n');
}
return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值