pta 编程题16 Saving James Bond - Easy Version

Posted bloglxc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了pta 编程题16 Saving James Bond - Easy Version相关的知识,希望对你有一定的参考价值。

其它pta数据结构编程题请参见:pta

题目

主要用到了深度优先搜索。

 1 #include <iostream>
 2 using namespace std;
 3 
 4 struct Vertex
 5 {
 6     int x;
 7     int y;
 8     bool marked;
 9 }G[100];
10 
11 int N; //总鳄鱼数
12 int D; //可以跳的距离
13 bool dfs(Vertex& v);
14 bool firstJump(Vertex v);
15 bool jump(Vertex v1, Vertex v2);
16 bool success(Vertex v); //可以跳到岸上
17 
18 int main()
19 {
20     int i;
21     cin >> N >> D;
22     for (i = 0; i < N; i++)
23         cin >> G[i].x >> G[i].y;
24 
25     bool canEscape = false;
26     for (i = 0; i < N; i++)
27     {
28         if (!G[i].marked && firstJump(G[i]))
29             canEscape = dfs(G[i]);
30         if (canEscape) break;
31     }
32     if (canEscape) cout << "Yes";
33     else cout << "No";
34     return 0;
35 }
36 
37 bool firstJump(Vertex v)
38 {
39     return v.x * v.x + v.y * v.y <= (15 + D) * (15 + D);
40 }
41 
42 bool dfs(Vertex& v)
43 {
44     bool canEscape = false;
45     v.marked = true;
46     if (success(v)) return true;
47     for (int i = 0; i < N; i++)
48     {
49         if (!G[i].marked && jump(v, G[i]))
50             canEscape = dfs(G[i]);
51         if (canEscape) break;
52     }
53     return canEscape;
54 }
55 
56 bool success(Vertex v)
57 {
58     if (v.x <= D - 50 || v.x >= 50 - D || v.y <= D - 50 || v.y >= 50 - D)
59         return true;
60     return false;
61 }
62 
63 bool jump(Vertex v1, Vertex v2)
64 {
65     return (v1.x - v2.x) * (v1.x - v2.x) + (v1.y - v2.y) * (v1.y - v2.y) <= D*D;
66 }

 

以上是关于pta 编程题16 Saving James Bond - Easy Version的主要内容,如果未能解决你的问题,请参考以下文章

PTA 06-图2 Saving James Bond - Easy Version (25分)

PTA 07-图5 Saving James Bond - Hard Version (30分)

数据结构图 —— 编程作业 02 :Saving James Bond

数据结构图 —— 编程作业 05 :Saving James Bond - Hard Version

05-图2. Saving James Bond - Easy Version (25)

07-图5 Saving James Bond