【HDOJ】1983 Kaitou Kid - The Phantom Thief (2)

时间:2023-03-08 15:52:08

不仅仅是DFS,还需要考虑可以走到终点。同时,需要进行预处理。至多封闭点数为起点和终点的非墙壁点的最小值。

 #include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <queue>
using namespace std; typedef struct node_st {
int x, y, t, flg;
node_st() {}
node_st(int xx, int yy, int tt, int fflg) {
x=xx; y=yy; t=tt; flg=fflg;
}
} node_st; char map[][];
char visit[][][];
int direct[][] = {{-,},{,},{,-},{,}};
int n, m, time, fmin;
int begx, begy, endx, endy; bool check(int x, int y) {
if (x< || x>=n || y< || y>= m)
return false;
return true;
} bool bfs() {
queue<node_st> que;
int x, y, t, flg;
int i;
node_st node; memset(visit, , sizeof(visit));
que.push(node_st(begx, begy, , ));
visit[begx][begy][] = ; while ( !que.empty() ) {
node = que.front();
que.pop();
t = node.t;
if (t == time)
break;
for (i=; i<; ++i) {
x = node.x + direct[i][];
y = node.y + direct[i][];
flg = node.flg;
if ( !check(x, y) )
continue;
if (map[x][y] != '#') {
if (map[x][y] == 'E' && flg==)
return true;
if (map[x][y] == 'J')
flg = ;
if (t<time && !visit[x][y][flg]) {
visit[x][y][flg] = ;
que.push(node_st(x, y, t+, flg));
}
}
}
} return false;
} void printmap() {
for (int i=; i<n; ++i)
printf("\t%s\n", map[i]);
} int dfs(int t, int cur) {
int flg = ;
char ch; if (t >= fmin)
return ; for (int i=; i<n; ++i) {
for (int j=; j<m; ++j) {
if (map[i][j]=='.' || map[i][j] == 'J') {
ch = map[i][j];
map[i][j] = '#';
if (cur == t) {
//printmap();
if ( !bfs() ) {
fmin = (t<fmin) ? t:fmin;
return ;
}
}
if (cur < t)
flg = dfs(t, cur+);
map[i][j] = ch;
}
if (flg)
return ;
}
} return ;
} int pre() {
int i, x, y, tmp1, tmp2; tmp1 = ;
for (i=; i<; ++i) {
x = begx + direct[i][];
y = begy + direct[i][];
if ( check(x, y) && (map[x][y]=='.'||map[x][y]=='J'))
tmp1++;
} tmp2 = ;
for (i=; i<; ++i) {
x = endx + direct[i][];
y = endy + direct[i][];
if ( check(x, y) && (map[x][y]=='.'||map[x][y]=='J'))
tmp2++;
} return tmp1<tmp2 ? tmp1 : tmp2;
} int main() {
int case_n;
int i, j; scanf("%d", &case_n); while (case_n--) {
scanf("%d %d %d%*c", &n, &m, &time);
for (i=; i<n; ++i) {
scanf("%s", map[i]);
for (j=; j<m; ++j) {
if (map[i][j] == 'S') {
begx = i;
begy = j;
}
if (map[i][j] == 'E') {
endx = i;
endy = j;
}
}
}
if ( !bfs() ) {
printf("0\n");
continue;
}
fmin = pre();
//printf("pre:%d\n", fmin);
dfs(,);
//printf("1:%d\n", fmin);
dfs(,);
//printf("2:%d\n", fmin);
dfs(,);
printf("%d\n", fmin);
} return ;
}