hrbust 1286 迷宫与宝藏【bfs】
题目连接: http://acm.hrbust.edu.cn/index.php?m=ProblemSet&a=showProblem&problem_id=1286
代码:
#include<stdio.h> #include<limits.h> #include<string.h> #include<queue> using namespace std; int step[101][101][101]; //行,列,价值。step记录最小步数。 char map[101][101]; int n, m, tot; struct now { int x, y, v; }; int dir[4][2] = { {1, 0}, {0 ,1}, {0, -1}, {-1, 0} }; int bfs(struct now a) { a.v = 0; step[a.x][a.y][a.v] = 0; queue<struct now> Q; Q.push( a ); while( !Q.empty() ) { struct now tmp = Q.front(); Q.pop(); for(int i = 0; i < 4; i++) { struct now tmp2; tmp2.x = tmp.x + dir[i][0]; tmp2.y = tmp.y + dir[i][1]; if(tmp2.x >= 0 && tmp2.x < n && tmp2.y >= 0 && tmp2.y < m && map[tmp2.x][tmp2.y] != '#') { tmp2.v = tmp.v + map[tmp2.x][tmp2.y] - '0'; if(tmp2.v == tot) return step[tmp.x][tmp.y][tmp.v] + 1; if(tmp2.v > tot) continue; if(step[tmp2.x][tmp2.y][tmp2.v] > step[tmp.x][tmp.y][tmp.v] + 1) { step[tmp2.x][tmp2.y][tmp2.v] = step[tmp.x][tmp.y][tmp.v] + 1; Q.push( tmp2 ); } } } } return -1; } int main() { int T; scanf("%d%*c", &T); while( T-- ) { scanf("%d %d%*c", &n, &m); n++; m++; for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { for(int k = 0; k < 101; k++) { step[i][j][k] = INT_MAX; } } } struct now a; for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { scanf("%c", &map[i][j]); if(map[i][j] == '*') { a.x = i; a.y = j; map[i][j] = '0'; } if(map[i][j] == '.') { map[i][j] = '0'; } } scanf("%*c"); } scanf("%d%*c", &tot); if(tot == 0) { printf("0\n"); } else { printf("%d\n", bfs(a)); } } return 0; }