#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;
}
HDOJ-1728 逃离迷宫(BFS + 转弯)
最新推荐文章于 2018-09-27 13:36:11 发布