zoukankan      html  css  js  c++  java
  • 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;
    }


  • 相关阅读:
    23种设计模式总篇
    23种设计模式之抽象工厂
    23种设计模式之原型模式
    23种设计模式之适配器模式
    23种设计模式之工厂模式
    23种设计模式之模板方法
    Cloudera Manager 5和CDH5离线安装
    ArrayList vs. LinkedList vs. Vector
    在Java中怎样把数组转换为ArrayList?
    两个有序数组的中位数 【算法】
  • 原文地址:https://www.cnblogs.com/vongang/p/2221206.html
Copyright © 2011-2022 走看看