HDOJ-1728 逃离迷宫(BFS + 转弯)

#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;

const int MAX_ROW = 100;
const int MAX_COL = 100;
const int MOVE[4][2] = {
    //0 = up, 1 = down, 2 = left, 3 = right
    {-1, 0}, {1, 0}, {0, -1}, {0, 1} 
};

struct State{
    int row;    //current row
    int col;    //current column
    int dir;    //current direction
    int turn;   //how many turns already taken to reach this state
};

int  m, n;                     //row and col of map
char map[MAX_ROW][MAX_COL + 1];//map
int  cost[MAX_ROW][MAX_COL][4];//record the least turning need to reach this state

inline bool isUnreachable(int row, int col)
{
    return row < 0 || row >= m ||
           col < 0 || col >= n ||
           map[row][col] != '.';
}
bool isReachable(int srcRow, int srcCol, int desRow, int desCol, int maxTurn)
{
    if(srcRow == desRow && srcCol == desCol) return true;
    
    State now, nex;
    queue<State> q;
//step 0: initialize cost
    memset(cost, 0xff, sizeof(cost));
//step 1: initialize starting state
    now.row = srcRow;
    now.col = srcCol;
    now.turn = 0;
    for(int i = 0; i < 4; ++i){
        now.dir = i;
        cost[srcRow][srcCol][i] = 0;
        q.push(now);
    }
//step 2: bfs to find possible path
    while(!q.empty()){
        now = q.front();
        q.pop();
        //check if now at destination
        if(now.row == desRow && now.col == desCol) return true;
        //move to next position
        for(int i = 0; i < 4; ++i){
            nex.row = now.row + MOVE[i][0];
            nex.col = now.col + MOVE[i][1];
            //check if out of border
            if(isUnreachable(nex.row, nex.col)) continue;
            else nex.dir = i;
            //check if too many turns already
            if(now.dir == i) nex.turn = now.turn;
            else if(now.turn == maxTurn) continue;
            else nex.turn = now.turn + 1;
            //check if better than least cost
            if(cost[nex.row][nex.col][nex.dir] < 0 ||
               nex.turn < cost[nex.row][nex.col][nex.dir]){
                cost[nex.row][nex.col][nex.dir] = nex.turn;
                q.push(nex);
            }
        }
    }
    return false;
}


int main()
{
    int test, sx, sy, dx, dy, k;
    
    for(scanf("%d", &test); test; --test){
        scanf("%d %d", &m, &n);
        while(getchar() != '\n') ;
        for(int i = 0; i < m; ++i) gets(map[i]);
        scanf("%d %d %d %d %d", &k, &sx, &sy, &dx, &dy);
        if(isReachable(sy - 1, sx - 1, dy - 1, dx - 1, k)) puts("yes");
        else puts("no");
    }
    
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值