HDU 1429
题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=1429
题意:
迷宫,从起点走向终点。有墙,有门禁,有钥匙。
思路:
BFS + 状压
源码:
#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <algorithm>
#include <iostream>
#include <queue>
using namespace std;
struct State
{
int state, step, x, y;
void init(int _x, int _y, int _step, int _state){x = _x, y = _y, step = _step, state = _state;}
};
queue<State>que;
int vis[25][25][1<<('j'-'a' + 1)];
char str[25][25];
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, -1, 0, 1};
int n, m;
bool valid_pos(int x, int y)
{
if(x < 0 || x >= n)
return false;
if(y < 0 || y >= m)
return false;
return true;
}
int main()
{
int t;
while(scanf("%d%d%d", &n, &m, &t) != EOF){
int sx, sy;
sx = -1, sy = -1;
for(int i = 0 ; i < n ; i++){
scanf("%s", str[i]);
if(sx == -1){
for(int j = 0 ; j < m ; j++){
if(str[i][j] == '@'){
sx = i;
sy = j;
}
}
}
}
memset(vis, 0, sizeof(vis));
while(!que.empty()){
que.pop();
}
State org;
org.init(sx, sy, 0, 0);
que.push(org);
vis[sx][sy][0] = 1;
int ans = -1;
while(!que.empty()){
org = que.front(); que.pop();
// printf("org.x = %d, org.y = %d, org.state = %d, org.step = %d\n", org.x, org.y, org.state, org.step);
int tx, ty;
for(int i = 0 ; i < 4 ; i++){
tx = org.x + dx[i];
ty = org.y + dy[i];
if(valid_pos(tx, ty)){
if(str[tx][ty] == '^'){
ans = org.step + 1;
break;
}
if(str[tx][ty] == '*')
continue;
int tstate = org.state;
if(str[tx][ty] >= 'a' && str[tx][ty] <= 'j'){
tstate = tstate | (1 << (str[tx][ty] - 'a'));
}
if(str[tx][ty] >= 'A' && str[tx][ty] <= 'J'){
if(! ((1 << (str[tx][ty] - 'a') & tstate)) )
continue;
}
if(vis[tx][ty][tstate])
continue;
vis[tx][ty][tstate] = 1;
State temp;
temp.init(tx, ty, org.step + 1, tstate);
que.push(temp);
}
}
if(ans != -1)
break;
}
if(ans < t && ans != -1)
printf("%d\n", ans);
else
printf("-1\n");
}
return 0;
}