Exemplo n.º 1
0
void pathFinder::findPath( p2DArray maze, const vector2 &start, const vector2 &end )
{
	// 起点或者终点无效,直接返回
	if( !isPointValid( start, maze ) ||
		!isPointValid( end, maze ) )
	{
		return;
	}
	else
	{
		clearPath();

		char mazeCopy[ROW][CEL];
		memcpy( dirMap, maze, sizeof(char)*ROW*CEL );
		memcpy( mazeCopy, maze, sizeof(char)*ROW*CEL );

		MyQueue openList;
		openList.push_back( start );

		vector2 curPos;
		vector2 temp;

		while ( 1 )
		{
			openList.pop_front( curPos );

			// 碰到了终点,可以停止了
			if( curPos == end )
			{
				dirMap[start.x][start.y] = MS_START;
//				readPathFromDirMap( end );
				return;
			}

			// 当前点有效才需要扩展
			if( isPointValid( curPos, mazeCopy ) )
			{
				mazeCopy[curPos.x][curPos.y] = MS_WALKED;

				int curDir = 0;
				while ( curDir < 4 )
				{
					temp.x = curPos.x + dirArray[curDir].x;
					temp.y = curPos.y + dirArray[curDir].y;
					if( isPointValid( temp, mazeCopy ) )
					{
						openList.push_back( temp );
						// 标记当前节点的上一节点
						dirMap[temp.x][temp.y] = getOppositeDir( curDir );
					}

					++curDir;
				}
			}

			// 扩展列表为空,只能退出了
			if( openList.isEmpty() )
			{
				return;
			}
		}
	}
}