Gui*_*osa 1 c++ recursion a-star
我有一个A*算法的结构,它由以下定义:
typedef struct matriz{
int g,h,f;
bool isBarrier, isStart, isEnd;
}matrix;
Run Code Online (Sandbox Code Playgroud)
我已经用这个结构制作了一个矩阵,并将所有初始值设为0.
matrix n[8][8];
Run Code Online (Sandbox Code Playgroud)
然后我做了一个算法来计算起始位置到当前位置之间的距离.
为此我使用了递归方法,因为步骤将是到达该位置所需的步骤数量,每次计算另一个位置时它将增加:
bool checkbounds(int x, int y){
if(x>=0 && x<=totalsize-1){
if(y>=0 && y<=totalsize-1) return true;
}
return false;
}
bool isGNull(int x, int y){
if(n[x][y].g==0)return true;
return false;
}
void countg(int x, int y, int steps){
if(checkbounds(x-1,y)){
if(isGNull(x-1,y)){
n[x-1][y].g=steps;
countg(x-1,y,steps+1);
}
}
if(checkbounds(x,y-1)){
if(isGNull(x,y-1)){
n[x][y-1].g=steps;
countg(x,y-1,steps+1);
}
}
if(checkbounds(x+1,y)){
if(isGNull(x+1,y)){
n[x+1][y].g=steps;
countg(x+1,y,steps+1);
}
}
if(checkbounds(x,y+1)){
if(isGNull(x,y+1)){
n[x][y+1].g=steps;
countg(x,y+1,steps+1);
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题是它应该在返回递归时返回初始步骤值.
预期的结果应该是这样的:
| 5 4 3 2 3 4 5 6 |
| 4 3 2 1 2 3 4 5 |
| 3 2 1 S 1 2 E 6 |
| 4 3 2 1 2 3 4 5 |
| 5 4 3 2 3 4 5 6 |
| 6 5 4 3 4 5 6 7 |
| 7 6 5 4 5 6 7 8 |
| 8 7 6 5 6 7 8 9 |
Run Code Online (Sandbox Code Playgroud)
其中S是起始位置,E是结束位置.
但我得到的是:
| 5 4 3 2 35 36 53 54 |
| 6 19 20 1 34 37 52 55 |
| 7 18 21 S 33 38 E 56 |
| 8 17 22 31 40 39 50 57 |
| 9 16 23 30 41 48 49 58 |
|10 15 24 29 42 47 60 59 |
|11 14 25 28 43 46 61 64 |
|12 13 26 27 44 45 62 63 |
Run Code Online (Sandbox Code Playgroud)
可能是一些逻辑错误,但我找到它有些麻烦,有人可以帮助我吗?
--EDIT--用户Elazar对算法的大小做了一定的改进,但仍然给出了与以前相同的结果.
bool checkbounds(int x, int y) {
return 0 <= x && x < totalsize
&& 0 <= y && y < totalsize;
}
void countg(int _x, int _y, int steps) {
static int d[] = {-1, 0, 1, 0};
for (int i = 0; i < 4; i++) {
int x = _x+d[i], y = _y+d[3-i];
if (checkbounds(x,y) && n[x][y].g==0) {
n[x][y].g=steps;
countg(x,y,steps+1);
}
}
}
Run Code Online (Sandbox Code Playgroud)
提前致谢.
您的递归算法将向上移动,然后向左移动,然后向下移动,然后向右移动,标记它到目前为止所经过的距离.再看看数字,你可以看到它所采用的路线.
| 5 <4 <3 <2 35 36 53 54 |
v ^
| 6 19>20 1 34 37 52 55 |
v ^ v ^
| 7 18 21 S 33 38 E 56 |
v ^ v
| 8 17 22 31 40 39 50 57 |
v ^ v
| 9 16 23 30 41 48 49 58 |
v ^ v
|10 15 24 29 42 47 60 59 |
v ^ v
|11 14 25 28 43 46 61 64 |
v ^ v
|12>13 26>27 44 45 62 63 |
Run Code Online (Sandbox Code Playgroud)
然后,当它最终到达右下角时,它会展开堆栈而不会继续前进,因为所有内容都有一个数字.这称为深度优先搜索.
最简单的改变是将你的算法改为实际工作,就是检查当前steps是否比前一个短steps,而不是前一个steps是"null".但用patashu的话说,"这将是极其低效的".
这个算法甚至没有远离A*,并且很难看出它如何变成一个.A*是广度优先搜索,需要您以交错方式执行多个路径.我非常建议从头开始.