-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathA_algo.cpp
124 lines (118 loc) · 3.11 KB
/
A_algo.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#include "unifindmap.h"
#include <vector>
#include <queue>
#include "math.h"
struct myPoint
{
int x=0,y=0;
int cost=60000;
int tcost=0;
myPoint* Father=nullptr;
bool operator > (const myPoint &a) const
{
return tcost > a.tcost;
}
};
bool is_moveable(int x1,int y1,int c,QPair<bool,bool> M[40][30])
{
switch (c)
{
case 0://Up
if(M[x1][y1-1].second)
return true;
break;
case 1://Left
if(M[x1-1][y1].first)
return true;
break;
case 2://Down
if(M[x1][y1].second)
return true;
break;
case 3://Right
if(M[x1][y1].first)
return true;
break;
default:
break;
}
return false;
}
int p_cost(int x1, int y1)
{
return sqrt((x1-38)*(x1-38) + (y1-28)*(y1-28));
}
std::vector<QPair<int,int> > A_algo(QPair<bool,bool> M[40][30],int x,int y)
{
bool reach[40][30];
memset(reach,0,sizeof(reach));
reach[x][y]=true;
auto start = new myPoint();
start->x = x;
start->y = y;
start->cost = 0;
start->tcost = p_cost(x,y) + start->cost;
std::priority_queue<myPoint*,std::vector<myPoint*>,std::greater<myPoint*> > Q;
Q.push(start);
while(!Q.empty())
{
auto p = Q.top();
if (p->x==38 && p->y==28)
{
std::vector<QPair<int,int> > route;
auto t = p;
while(t!=nullptr)
{
route.push_back(QPair<int,int>(t->x,t->y));
t = t->Father;
}
return route;
}
Q.pop();
if(is_moveable(p->x,p->y,0,M) && !reach[p->x][p->y-1]) //Up
{
reach[p->x][p->y-1]=true;
auto newP = new myPoint();
newP->x=p->x;
newP->y=p->y -1;
newP->cost = p->cost + 1;
newP->tcost = p_cost(newP->x,newP->y) + newP->cost;
newP->Father = p;
Q.push(newP);
}
if(is_moveable(p->x,p->y,2,M) && !reach[p->x][p->y+1]) //Down
{
reach[p->x][p->y+1]=true;
auto newP = new myPoint();
newP->x=p->x;
newP->y=p->y +1;
newP->cost = p->cost + 1;
newP->tcost = p_cost(newP->x,newP->y) + newP->cost;
newP->Father = p;
Q.push(newP);
}
if(is_moveable(p->x,p->y,1,M) && !reach[p->x-1][p->y]) //Left
{
reach[p->x-1][p->y]=true;
auto newP = new myPoint();
newP->x=p->x -1;
newP->y=p->y;
newP->cost = p->cost + 1;
newP->tcost = p_cost(newP->x,newP->y) + newP->cost;
newP->Father = p;
Q.push(newP);
}
if(is_moveable(p->x,p->y,3,M) && !reach[p->x+1][p->y]) //Right
{
reach[p->x+1][p->y]=true;
auto newP = new myPoint();
newP->x=p->x +1;
newP->y=p->y;
newP->cost = p->cost + 1;
newP->tcost = p_cost(newP->x,newP->y) + newP->cost;
newP->Father = p;
Q.push(newP);
}
}
return std::vector<QPair<int,int> >();
}