解题思路:
直接的bfs,因为和时间有关,需要采用优先队列.
#include <iostream> #include <cstring> #include <cstdlib> #include <cstdio> #include <algorithm> #include <vector> #include <queue> #include <set> #include <map> #include <stack> using namespace std; const int MAXN = 500 + 10; char G[MAXN][MAXN]; int N, M, D; struct Node { int x, y, time; bool operator < (const Node& rhs)const { return time > rhs.time; } }; bool vis[MAXN][MAXN]; int g[][2] = {{-1,0},{1,0},{0,-1},{0,1}}; int bfs(int sx, int sy) { memset(vis, false, sizeof(vis)); priority_queue<Node> Q; while(!Q.empty()) Q.pop(); vis[sx][sy] = 1; Node u, v; u.x = sx, u.y = sy, u.time = 1; Q.push(u); while(!Q.empty()) { u = Q.top(); Q.pop(); for(int i=0;i<4;i++) { int x = u.x + g[i][0]; int y = u.y + g[i][1]; if(x < 1 || x > N || y < 1 || y > M) return u.time; if(vis[x][y] || G[x][y] == '#') continue; if(G[x][y] == '@') { v.x = x, v.y = y, v.time = u.time + D + 1; vis[x][y] = true; Q.push(v); } if(G[x][y] == '.') { vis[x][y] = true; v.x = x, v.y = y, v.time = u.time + 1; Q.push(v); } } } return -1; } int main() { int T; scanf("%d", &T); while(T--) { int sx, sy; scanf("%d%d%d", &N, &M, &D); for(int i=1;i<=N;i++) { for(int j=1;j<=M;j++) { scanf(" %c", &G[i][j]); if(G[i][j] == 'S') { sx = i; sy = j; } } } /*for(int i=1;i<=N;i++) { for(int j=1;j<=M;j++) cout<<G[i][j]; cout<<endl; }*/ int ans = bfs(sx, sy); printf("%d\n", ans); } return 0; }
时间: 2024-10-30 04:50:10