Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 2699    Accepted Submission(s): 813
Special Judge

    本题其实并不难,就是搜索,但是最麻烦的估计就是记录路径。我用的是广搜,在每一个节点中记录下他的前驱节点,这样回溯很容易找到路径。

代码:

 

1 #include<stdio.h>
2 #include<ctype.h>
3 #include<queue>
4 #include<stack>
5  using namespace std;
6  int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
7  int n,m;
8 struct node
9 {
10 int time;
11 int x, y;
12 int prex,prey;
13 char data;
14 int fight;
15 bool operator <(const node &a) const
16 {
17 return a.time<time;
18 }
19 }s[105][105];
20 typedef struct t
21 {
22 int x, y;
23 }T;
24 node cur1;T cur2,next2;
25 int bfs()
26 {
27 priority_queue<node> qu;
28 int i,x1,y1;
29 s[0][0].time=0;
30 qu.push(s[0][0]);
31 while(!qu.empty ())
32 {
33 cur1=qu.top();
34 qu.pop ();
35 if(cur1.x==n-1 && cur1.y==m-1)
36 return 1;
37 for(i=0;i<4;i++)
38 {
39 x1=cur1.x+dir[i][0];
40 y1=cur1.y+dir[i][1];
41 if(x1>=0 && x1<n && y1>=0 && y1<m)
42 {
43 if(s[x1][y1].data=='.' && s[x1][y1].time>cur1.time+1)
44 {
45 s[x1][y1].time=cur1.time+1;
46 s[x1][y1].prex=cur1.x;
47 s[x1][y1].prey=cur1.y;
48 qu.push(s[x1][y1]);
49 }
50 else if(isdigit(s[x1][y1].data) && s[x1][y1].time>cur1.time+s[x1][y1].data-'0')
51 {
52 s[x1][y1].time=cur1.time+s[x1][y1].data-'0'+1;
53 s[x1][y1].fight=1;
54 s[x1][y1].prex=cur1.x;
55 s[x1][y1].prey=cur1.y;
56 qu.push(s[x1][y1]);
57 }
58 }
59 }
60 }
61
62 return 0;
63 }
64 int main()
65 {
66 int i,j;char a;
67 while(scanf("%d%d",&n,&m)!=EOF)
68 {
69 for(i=0;i<n;i++)
70 {
71 getchar();
72 for(j=0;j<m;j++)
73 {
74 scanf("%c",&a);
75 s[i][j].data=a;
76 s[i][j].time=0xfffffff;
77 s[i][j].x=i;
78 s[i][j].y=j;
79 s[i][j].fight=0;
80 }
81 }
82 if(bfs())
83 {
84 stack<T> st;
85 cur2.x=n-1;
86 cur2.y=m-1;
87 st.push(cur2);
88 while(1)
89 {
90 cur2=st.top ();
91 if(cur2.x==0 && cur2.y==0)
92 break;
93 next2.x=s[cur2.x][cur2.y].prex;
94 next2.y=s[cur2.x][cur2.y].prey;
95 st.push(next2);
96 }
97 printf("It takes %d seconds to reach the target position, let me show you the way.\n",s[n-1][m-1].time);
98 st.pop();
99 while(!st.empty ())
100 {
101 cur2=st.top ();
102 if(s[cur2.x][cur2.y].fight==1)
103 {
104 printf("%ds:(%d,%d)->(%d,%d)\n",s[cur2.x][cur2.y].time-(s[cur2.x][cur2.y].data-'0'),s[cur2.x][cur2.y].prex ,s[cur2.x][cur2.y].prey,cur2.x,cur2.y);
105 for(i=1;i<=s[cur2.x][cur2.y].data-'0';i++)
106 printf("%ds:FIGHT AT (%d,%d)\n",s[cur2.x][cur2.y].time+i-(s[cur2.x][cur2.y].data-'0'),cur2.x ,cur2.y);
107 }
108 else
109 printf("%ds:(%d,%d)->(%d,%d)\n",s[cur2.x][cur2.y].time,s[cur2.x][cur2.y].prex ,s[cur2.x][cur2.y].prey,cur2.x,cur2.y);
110 st.pop ();
111 }
112 }
113 else
114 {
115 printf("God please help our poor hero.\n");
116 }
117 printf("FINISH\n");
118 }
119 return 0;
120 }
121
122
123