A*算法基础

A*算法笔记:

最常用的寻路算法

三个值:

  G:从出发方格到当前方格的路径长度(假设图中方格长度为1)

  H:从当前方格到目标方格的路径长度估算,注意是“估算”。多种估算方法见下

  F:G+H,表示对路径总长度长度的估算

两个列表:

  openList:用于存储可移动的方格(节点)

  closeList:用于存储已经检查过的节点

下一个节点的选择:

  在openList中选择F值最小的方格

参考http://www.cnblogs.com/zhoug2020/p/3468167.html的这篇关于A*算法的讲解十分详细。

以这文章中的一幅图为题目用C++实现该算法。

class Square
{
	public:
		int parentx,parenty;
		int x, y;
		int F;
		int G;
		int H;
		int type;
public:
	Square(int x, int y) : parentx(-1),parenty(-1), F(-1), G(-1), H(-1), type(0) { this->x = x, this->y = y; }
	
};

bool operator<(Square a,Square b)
{
	return a.F > b.F;
}
bool operator==(Square a, Square b)
{
	return (a.x == b.x) && (a.y == b.y);
}
int _tmain(int argc, _TCHAR* argv[])
{
	vector<Square> closeList;
	priority_queue<Square> openList;
	int openAdd[6][7] = {0};
	Square* s[6][7];
	for (int i = 0; i < 6;i++)
	{
		for (int j = 0; j < 7;j++)
		{
			s[i][j] = new Square(i,j);
		}
	}
	s[4][1]->type = 1;
	s[1][3]->type = 1;
	s[2][3]->type = 1;
	s[3][3]->type = 1;
	s[4][3]->type = 1;

	s[3][1]->G = 0;
	s[3][1]->H = 0;
	openList.push(*s[3][1]);
	openAdd[3][1] = 1;

	do 
	{
		Square curr = openList.top();
		closeList.push_back(curr);
		openList.pop();

		vector<Square>::iterator i = find(closeList.begin(), closeList.end(), *s[4][5]);
		if (i != closeList.end())
		{
			break;
		}

		vector<Square> adj;
		int x=curr.x, y=curr.y;
		if ((x+1)<=5&&s[x+1][y]->type==0)
		{
			adj.push_back(*s[x + 1][y]);
		}
		if ((x-1)>=0&&s[x-1][y]->type==0)
		{
			adj.push_back(*s[x - 1][y]);
		}
		if ((y-1)>=0&&s[x][y-1]->type==0)
		{
			adj.push_back(*s[x][y-1]);
		}
		if ((y + 1) <= 6 && s[x][y + 1]->type == 0)
		{
			adj.push_back(*s[x][y + 1]);
		}
		for (auto iter = adj.begin(); iter != adj.end();iter++)
		{
			cout << "(" << (*iter).x << "," << (*iter).y << ")  ";
		}
		cout << endl;

		for (auto t = adj.begin(); t != adj.end();t++)
		{
			if (closeList.end() != find(closeList.begin(), closeList.end(), (*t)))
			{
				cout << "no:" <<"(" << (*t).x << "," << (*t).y << ")  " << endl;
				continue;
			}
			if (openAdd[(*t).x][(*t).y]==0)
			{
				(*t).G = curr.G + 1;
				(*t).H = abs((*t).x - 4) + abs((*t).y - 5);
				(*t).F = (*t).G + (*t).H;
				s[(*t).x][(*t).y]->parentx = curr.x;
				s[(*t).x][(*t).y]->parenty = curr.y;
				cout << "yes and parent:" << endl
					<< (*t).x << "," << (*t).y << "  " << (*t).parentx << "," << (*t).parenty << endl;
				openList.push((*t));
				openAdd[(*t).x][(*t).y] = 1;
			}
		}
	} while (!openList.empty());

	cout << "result:"<<endl;
	Square* temp = s[4][5];
	while (temp->parentx!=-1)
	{
		cout << "(" << temp->x << temp->y << ")" << endl;
		temp = s[temp->parentx][temp->parenty];
	}

	//while (!openList.empty())
	//{
	//	cout<<static_cast<Square>(openList.top()).F<<" ";
	//	openList.pop();
	//}
	//cout << endl;

	system("pause");
	return 0;
}

  代码贼烂。

 

posted on 2017-12-12 15:51  不迷阿狸  阅读(187)  评论(0)    收藏  举报

导航