题目链接
5 6 .XX.1. ..X.2. 2...X. ...XX. XXXXX. 5 6 .XX.1. ..X.2. 2...X. ...XX. XXXXX1 5 6 .XX... ..XX1. 2...X. ...XX. XXXXX.
It takes 13 seconds to reach the target position, let me show you the way. 1s:(0,0)->(1,0) 2s:(1,0)->(1,1) 3s:(1,1)->(2,1) 4s:(2,1)->(2,2) 5s:(2,2)->(2,3) 6s:(2,3)->(1,3) 7s:(1,3)->(1,4) 8s:FIGHT AT (1,4) 9s:FIGHT AT (1,4) 10s:(1,4)->(1,5) 11s:(1,5)->(2,5) 12s:(2,5)->(3,5) 13s:(3,5)->(4,5) FINISH It takes 14 seconds to reach the target position, let me show you the way. 1s:(0,0)->(1,0) 2s:(1,0)->(1,1) 3s:(1,1)->(2,1) 4s:(2,1)->(2,2) 5s:(2,2)->(2,3) 6s:(2,3)->(1,3) 7s:(1,3)->(1,4) 8s:FIGHT AT (1,4) 9s:FIGHT AT (1,4) 10s:(1,4)->(1,5) 11s:(1,5)->(2,5) 12s:(2,5)->(3,5) 13s:(3,5)->(4,5) 14s:FIGHT AT (4,5) FINISH God please help our poor hero. FINISH
#include <iostream> #include <cstring> #include <cstdio> #include <algorithm> #include <cmath> #include <cstdlib> #include <limits> #include <queue> #include <stack> using namespace std; #define N 150 #define INF 0xfffffff #define PI acos (-1.0) #define EPS 1e-8 const int dir1[8][2] = {{-2, -1}, {-2, 1}, {-1, -2}, {-1, 2}, {1, -2}, {1, 2}, {2, -1}, {2, 1}}; const int dir2[4][2] = {{-1, 0}, {0, -1}, {0, 1}, {1, 0}}; struct node { int x, y, t; bool operator < (const node &c) const { return t > c.t; } }sa, stu[N][N]; int n, m, k, vis[N][N], time; char maps[N][N]; int BFS (); void DFS (int x, int y, int ans); int main () { while (cin >> n >> m) { for (int i=0; i<n; i++) for (int j=0; j<m; j++) cin >> maps[i][j]; sa = (node){0, 0, 0}; int ans = BFS (); if (ans >= 0) { printf ("It takes %d seconds to reach the target position, let me show you the way.\n", sa.t); DFS (n-1, m-1, ans); } else puts("God please help our poor hero."); puts("FINISH"); } return 0; } int BFS () { memset(vis, 0, sizeof (vis)); priority_queue <node> que; que.push(sa); vis[sa.x][sa.y] = 1; while (que.size()) { sa = que.top(); que.pop(); if (sa.x == n-1 && sa.y == m-1) return sa.t; for (int i=0; i<4; i++) { node q = sa; q.x += dir2[i][0]; q.y += dir2[i][1]; if (!vis[q.x][q.y] && maps[q.x][q.y] != 'X' && q.x>=0 && q.x<n && q.y>=0 && q.y<m) { stu[q.x][q.y] = sa; if (maps[q.x][q.y] == '.') stu[q.x][q.y].t = 0; else stu[q.x][q.y].t = maps[q.x][q.y] - '0'; q.t += stu[q.x][q.y].t + 1; vis[q.x][q.y] = 1; que.push(q); } } } return -1; } void DFS (int x, int y, int ans) { if (x == 0 && y == 0 && ans == 0) return; if (stu[x][y].t) ans -= stu[x][y].t; DFS (stu[x][y].x, stu[x][y].y, ans-1); printf ("%ds:(%d,%d)->(%d,%d)\n", ans++, stu[x][y].x, stu[x][y].y, x, y); while (stu[x][y].t--) printf ("%ds:FIGHT AT (%d,%d)\n", ans++, x, y); }