bfs.题目做的不细心,好多小错误。尤其注意起始点就是边界的情况。wa了八次。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std; #define MAXN 85 typedef struct node_st {
int x, y;
int d, s;
node_st() {}
node_st(int xx, int yy, int dd, int ss) {
x = xx; y = yy; d = dd; s = ss;
}
} node_st; char map[MAXN][MAXN];
bool visit[][MAXN][MAXN];
int direct[][] = {-,,,,,-,,};
int n, m; int bfs(int sx, int sy) {
int i, j, nx, ny;
queue<node_st> que;
node_st node;
bool flag; if (sx== || sx==n- || sy== || sy==m-)
return ;
memset(visit, false, sizeof(visit));
visit[][sx][sy] = visit[][sx][sy] = visit[][sx][sy] = visit[][sx][sy] = true; for (i=; i<; ++i) {
nx = sx + direct[i][];
ny = sy + direct[i][];
if (nx< || nx>=n || ny< || ny>=m)
continue;
if (map[nx][ny] != '#') {
que.push(node_st(nx, ny, i, ));
visit[i][nx][ny] = true;
}
} while ( !que.empty() ) {
node = que.front();
que.pop();
flag = true;
// node.d = 0/1 -> south/north
// node.d = 2/3 -> east/west
j = (node.d&) ? :;
for (i=j; i<j+; ++i) {
nx = node.x + direct[i][];
ny = node.y + direct[i][];
if (nx< || nx>=n || ny< || ny>=m)
continue;
if (map[nx][ny] != '#') {
flag = false;
if (!visit[i][nx][ny]) {
if (nx== || nx==n- || ny== || ny==m-)
return node.s+;
que.push(node_st(nx, ny, i, node.s+));
visit[i][nx][ny] = true;
}
}
}
if (flag) {
i = node.d;
nx = node.x + direct[i][];
ny = node.y + direct[i][];
if (nx< || nx>=n || ny< || ny>=m)
continue;
if (map[nx][ny]=='#' || visit[i][nx][ny])
continue;
if(nx== || nx==n- || ny== || ny==m-)
return node.s+;
que.push(node_st(nx, ny, i, node.s+));
visit[i][nx][ny] = true;
}
}
return -;
} int main() {
int t, x, y;
int i, j; scanf("%d", &t); while (t--) {
scanf("%d %d", &n, &m);
for (i=; i<n; ++i) {
scanf("%s", map[i]);
for (j=; j<m; ++j)
if (map[i][j] == '@') {
x = i;
y = j;
}
}
printf("%d\n", bfs(x, y));
} return ;
}