poj 1101 The Game

来源:互联网 发布:病理图像分析软件 编辑:程序博客网 时间:2024/04/29 12:16
//有趣的连连看游戏,广搜之 

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
int flag[78][78], map[78][78], step[78][78];
int w, h;
int move[4][2]={{1,0}, {-1,0}, {0,1}, {0,-1}};
struct Node{int r, c;}st, end;
void bfs(){
    queue <Node> q;
    q.push(st);
    Node head, next;
    while(!q.empty()){
        head=q.front();
        q.pop();
        for(int i=0; i<4; i++){
            next.r=head.r+move[i][0];
            next.c=head.c+move[i][1];
            if(next.r==end.r&&next.c==end.c){
                step[next.r][next.c]=step[head.r][head.c]+1;
                return;
            }
            if(flag[next.r][next.c])continue;
            while(next.c>=0&&next.r>=0&&next.r<=h+1&&next.c<=w+1&&!map[next.r][next.c]){
                if(!flag[next.r][next.c]){
                step[next.r][next.c]=step[head.r][head.c]+1;
                q.push(next);
                flag[next.r][next.c]=1;}
                next.r+=move[i][0];
                next.c+=move[i][1];
                if(next.r==end.r&&next.c==end.c){
                    step[next.r][next.c]=step[head.r][head.c]+1;
                    return;
                }
            }
        }
    }
}

int main(){
    freopen("1.txt", "r", stdin);
    int i, j, test=1, t;
    while(scanf("%d%d", &w, &h)&&w){
        getchar();
        char maze[78][78];
        memset(map, 0, sizeof(map));
        for(i=1; i<=h; i++){
            gets(maze[i]);
            for(j=0; j<w; j++)
            if(maze[i][j]=='X')
            map[i][j+1]=1;
        }
        printf("Board #%d:\n", test++);
        t=1;
        while(scanf("%d%d%d%d", &st.c, &st.r, &end.c, &end.r)&&st.c){
            memset(step, -1, sizeof(step));
            memset(flag, 0, sizeof(flag));
            flag[st.r][st.c]=1;
            step[st.r][st.c]=0;
            bfs();
            if(step[end.r][end.c]>=0)
            printf("Pair %d: %d segments.\n", t++, step[end.r][end.c]);
            else printf("Pair %d: impossible.\n", t++);
        }
        printf("\n");
    }
    return 0;
}

原创粉丝点击