HDU 2216 Game III(BFS,四维数组记录状态)

HDU 2216 Game III

#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;

int m,n;
int z1,z2,s1,s2;
char board[25][25];
int vis[25][25][25][25];//开四维数组记录数据
int to[4][2] = {1,0,-1,0,0,-1,0,1};//Z的走法
int to2[4][2] = {-1,0,1,0,0,1,0,-1};//S走相反路线

struct node {
    int x1, x2, y1, y2, step;
};

bool valid(int x,int y) {
    if(x<0 || y<0 || x>=n || y>=m || board[x][y] == 'X')
        return false;
    return true;
}

int ok(int x, int x1, int y, int y1) { //符合条件的状况
    if(x == x1 && y == y1)
        return 1;
    if(x == x1+1 && y == y1)
        return 1;
    if(x == x1-1 && y == y1)
        return 1;
    if(x == x1 && y == y1-1)
        return 1;
    if(x == x1 && y == y1+1)
        return 1;

    return 0;
}

int bfs() {

    int i;
    queue<node> Q;
    node cur,next;
    memset(vis, 0, sizeof(vis));

    cur.x1 = z1;
    cur.x2 = s1;
    cur.y1 = z2;
    cur.y2 = s2;
    cur.step = 0;
    vis[z1][z2][s1][s2] = 1;//四维数组记录行走状况
    Q.push(cur);

    while( !Q.empty() ) {
        cur = Q.front();
        Q.pop();

        if(ok(cur.x1, cur.x2, cur.y1, cur.y2))
            return cur.step;

        for(i = 0; i<4; i++) {
            next = cur;
            next.x1 = cur.x1 + to[i][0];
            next.y1 = cur.y1 + to[i][1];
            next.x2 = cur.x2 + to2[i][0];
            next.y2 = cur.y2 + to2[i][1];

            if(!valid(next.x1, next.y1))
                continue;

            if(!valid(next.x2,next.y2)) {//原地不动
                next.x2 = cur.x2;
                next.y2 = cur.y2;
            }

            if(vis[next.x1][next.y1][next.x2][next.y2])
                continue;

            vis[next.x1][next.y1][next.x2][next.y2] = 1;
            next.step = cur.step + 1;
            Q.push(next);
        }
    }
    return -1;
}

int main() {
    freopen("data.in", "r", stdin);
    while(scanf("%d%d",&n,&m) == 2) {
        int i,j;
        for(i = 0; i < n; i++) {
            scanf("%s", board[i]);

            for(j = 0; j < m ; j++) {
                if(board[i][j] == 'Z') {
                    z1 = i;
                    z2 = j;
                } else if(board[i][j] == 'S') {
                    s1 = i;
                    s2 = j;
                }
            }
        }
        int ans;
        ans = bfs();
        if(ans != -1)
            printf("%d\n",ans);
        else
            printf("Bad Luck!\n");
    }

    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值