コード例 #1
0
ファイル: Astar.cpp プロジェクト: owlwisp/GameTools
AStar* AStar::create(int ** map,int width,int height,bool useApproximateDest){
    AStar*  instance = new AStar(map,width,height,useApproximateDest);
    if (instance->init()) {
        return instance;
    }
    return nullptr;
}
コード例 #2
0
ファイル: myaStar.cpp プロジェクト: imousewyfzml/mylibrary
int main()
{
    out.open("log.txt");

    GameMap gmap(50,50);
    gmap.load_from_file("map.txt");

    NodePtr src(new Node(Coordinate(0,0)));
    NodePtr dest(new Node(Coordinate(4,3)));

    AStar astar;
    Path res;
    res = astar.get_shorten_path(gmap, src, dest);
    Path::iterator it = res.begin();
    for (; it!=res.end(); ++it)
    {
        cout << (*it)->get_coordinate() << " ";
        gmap.set_cell((*it)->get_coordinate().x,(*it)->get_coordinate().y,'>');
    }
    cout << endl;

    gmap.dump("map_res.txt");

    std::cout << "Hello world!" << std::endl;
    return 0;
}
コード例 #3
0
ファイル: test.cpp プロジェクト: johnjsb/IGVC2015
int main()
{
	int * main_map;
	AStar star;
	main_map = generateMap(10,10);
	bool result=star.Init(main_map, 10, 10);
	star.AStarSearch(1, 99);
	return 0;
}
コード例 #4
0
ファイル: Astar.cpp プロジェクト: owlwisp/GameTools
int main(){
    int **map = new int*[10 * 10];
    memset(map, 0, 10 * 10);

    AStar* astar = AStar::create(map,10,10);
    vector<ASNode> path = astar->findPath(0,1,9,9);
    astar->printPath(path);
    return 1;
}
コード例 #5
0
ファイル: main.cpp プロジェクト: n4mm0/AIProgramming
int main()
{	
	sf::RenderWindow window(sf::VideoMode(Constants::screenWidth, Constants::screenHeight), "Puzzle15");
	
	Puzzle15 puzzle;

	srand(time(NULL));
	Configuration config;

	int solvable[16] ={ 2, 5, 3, 4, 1, 10, 6, 8, 9, 14, 7, 11, 13, 16, 15, 12 };
	config.setConfiguration(solvable);

	puzzle.changeConfiguration(config);

	std::vector<Configuration> result;

	AStar solver;
	solver.Run(config, result);

	//puzzle.changeConfiguration(config);

	while (window.isOpen())
	{
		sf::Event event;
		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed)
				window.close();
			else
			{
				if (event.type == sf::Event::KeyPressed)
				{
					if (event.key.code == sf::Keyboard::Space)
					{
						if (!result.empty())
						{
							puzzle.changeConfiguration(result.back());
							result.pop_back();
						}
					}
				}
			}
		}

		window.clear();
		puzzle.draw(&window);
		window.display();
	}
	
	return 0;

	/*AStar algorithm;
	algorithm.Run();
	system("pause");*/
}
コード例 #6
0
ファイル: main.cpp プロジェクト: jbalestr42/42
int main(void)
{
	//Puzzle::PuzzleState g = { 1, 2, 3, 8, 0, 4, 7, 6, 5 };
	//Puzzle start(3);
	//Puzzle goal(g, 3);

	AStar aStar;
	AStar::PuzzleState start = { { 5, 2, 0, 4, 7, 6, 8, 3, 1 }, 0, 0 };
	//AStar::PuzzleState start = { { 2, 3, 4, 1, 8, 0, 7, 6, 5 }, 0, 0 };
	AStar::PuzzleState goal = { { 1, 2, 3, 8, 0, 4, 7, 6, 5 }, 0, 0 };
	aStar.solve(start, goal);

	return (0);
}
コード例 #7
0
ファイル: AStar.cpp プロジェクト: cubemoon/tower-skycity-one
AStar* AStar::create()
{
	AStar *pRet = new AStar();
	if (pRet && pRet->init())
	{
		pRet->autorelease();
		pRet->retain();
		return pRet;
	}
	else
	{
		delete pRet;
		pRet = NULL;
		return NULL;
	}	
}
コード例 #8
0
ファイル: main.cpp プロジェクト: hawkaa/ducking-wookie
int main(int argc, char** argv)
{
	AStar search;
	std::vector<RHNode*> results;

	gamestate start1;
	initTest1(start1);

	RHNode startNode1(start1);
	search.search(startNode1, results);

	printf("\nSuccess!\n");
	printf("\nSolution found with: \n");
	printf("%i moves", results.size());

}
コード例 #9
0
ファイル: AStarTest.cpp プロジェクト: shysean/Cocos2dxDemo
void GridLayer::testAstar()
{
    int startX;
    int startY;
    int endX;
    int endY;
    
    for (int r = 0; r < m_row; r++) {
        for (int c = 0; c < m_col; c++) {
            if(m_data[r][c] == FLAG_PATH)
            {
                m_data[r][c] = FLAG_EMPTY;
            }
            
            if (m_data[r][c] == FLAG_START)
            {
                startX = c;
                startY = r;
            }
            
            if (m_data[r][c] == FLAG_END)
            {
                endX = c;
                endY = r;
            }
        }
    }
    
    AStar* astar = new AStar(m_data, m_row, m_col);
    std::vector<Step*> moveList = astar->getPath(startX, startY, endX, endY);
    delete astar;
    
    // 删除起点终点
    moveList.pop_back();
    std::vector<Step*>::iterator iter = moveList.begin();
    moveList.erase(iter);
    
    // 赋值
    for (auto step : moveList)
    {
        m_data[step->gy][step->gx] = 1;
    }
    

    
    infoMap();
}
コード例 #10
0
AStar::AStar(const AStar& other) : numRows(other.getRowCount()), numCols(other.getColCount())
{
	map = new std::vector<std::vector<AStarNode*>*>(numRows);
	for(int i=0;i<numRows;i++)
	{
		map->at(i) = new std::vector<AStarNode*>(numCols);
		for (int j = 0; j < numCols; j++)
		{
			*(map->at(i)->at(j)) = *(other.map->at(i)->at(j));  //Double check this!!!!
																
		}
	}
	openList = new std::vector<AStarNode>(*other.getOpenList());
	closedList = new std::vector<AStarNode>(*other.getClosedList());
	goalNode = new AStarNode(other.getGoalNode());
	
}
コード例 #11
0
ファイル: Manager.cpp プロジェクト: benor1470/newRobotics
void Manager::calculateWayPoint(){
	vector<Waypoint> vecWaypoints;

	Graph gr = _map->GetGraphFromGrid();

	AStar a;
	Node* start = gr.GetNodeByPos(_slam->BestPrticle()->GetX(), _slam->BestPrticle()->GetY());
	Node* end = gr.GetNodeByPos(40, 47);
	vector<Node*> vec = a.GetShortestPath(start, end);
	for (int i = vec.size() - 1; i > 0; --i) {
		Waypoint wp(vec.operator [](i)->getXPos(),vec.operator [](i)->getYPos());
		cout << "AStar path: (" << wp.getX() << "," << wp.getY() << ")" << endl;
		vecWaypoints.push_back(wp);
	}
	cout << "Finished AStar path" << endl;

	this->_robot->SetWaypointVector(vecWaypoints);
}
コード例 #12
0
ファイル: navgraph.cpp プロジェクト: jmlich/fawkes
/** Search for a path between two nodes.
 * This function executes an A* search to find an (optimal) path
 * from node @p from to node @p to.
 * @param from node to search from
 * @param to goal node
 * @param estimate_func function to estimate the cost from any node to the goal.
 * Note that the estimate function must be admissible for optimal A* search. That
 * means that for no query may the calculated estimate be higher than the actual
 * cost.
 * @param cost_func function to calculate the cost from a node to another adjacent
 * node. Note that the cost function is directly related to the estimate function.
 * For example, the cost can be calculated in terms of distance between nodes, or in
 * time that it takes to travel from one node to the other. The estimate function must
 * match the cost function to be admissible.
 * @param use_constraints true to respect constraints imposed by the constraint
 * repository, false to ignore the repository searching as if there were no
 * constraints whatsoever.
 * @param compute_constraints if true re-compute constraints, otherwise use constraints
 * as-is, for example if they have been computed before to check for changes.
 * @return ordered vector of nodes which denote a path from @p from to @p to.
 * Note that the vector is empty if no path could be found (i.e. there is non
 * or it was prohibited when using constraints.
 */
fawkes::NavGraphPath
NavGraph::search_path(const NavGraphNode &from, const NavGraphNode &to,
		      navgraph::EstimateFunction estimate_func,
		      navgraph::CostFunction cost_func,
		      bool use_constraints, bool compute_constraints)
{
  if (! reachability_calced_)  calc_reachability();

  AStar astar;

  std::vector<AStarState *> a_star_solution;

  if (use_constraints) {
    constraint_repo_.lock();
    if (compute_constraints && constraint_repo_->has_constraints()) {
      constraint_repo_->compute();
    }

    NavGraphSearchState *initial_state =
      new NavGraphSearchState(from, to, this, estimate_func, cost_func,
			      *constraint_repo_);
    a_star_solution =  astar.solve(initial_state);
    constraint_repo_.unlock();
  } else {
    NavGraphSearchState *initial_state =
      new NavGraphSearchState(from, to, this, estimate_func, cost_func);
    a_star_solution =  astar.solve(initial_state);
  }

  std::vector<fawkes::NavGraphNode> path(a_star_solution.size());
  NavGraphSearchState *solstate;
  for (unsigned int i = 0; i < a_star_solution.size(); ++i ) {
    solstate = dynamic_cast<NavGraphSearchState *>(a_star_solution[i]);
    path[i] = solstate->node();
  }

  float cost =
    (! a_star_solution.empty())
      ? a_star_solution[a_star_solution.size() - 1]->total_estimated_cost
      : -1;

  return NavGraphPath(this, path, cost);
}
コード例 #13
0
Widget::Widget(QWidget *parent) :
	QWidget(parent),
	ui(new Ui::Widget)
{
	ui->setupUi(this);

	int size = 3;
	QVector<QVector< GameObject *> > cells;

	cells = QVector<QVector <GameObject*> > (size);
	for (int i = 0; i < cells.size(); i++)
	{
		cells[i] = QVector <GameObject*> (size);
		for (int j = 0; j < cells[i].size(); j++)
		{
			cells[i][j] = nullptr;
		}
	}

	cells[0][0] = new GameObject();
	cells[0][1] = new TreeObject();
	cells[0][2] = new TreeObject();
	cells[1][0] = new GameObject();
	cells[1][1] = new GameObject();
	cells[1][2] = new GameObject();
	cells[2][0] = new GameObject();
	cells[2][1] = new GameObject();
	cells[2][2] = new GameObject();

	AStar *astar = new AStar();
	astar->addCells(cells);

	QList<QPoint *> path = astar->calcualtePath(QPoint(0, 0), QPoint(2, 2));

	QList<QPoint *>::iterator i;

	for (i = path.begin(); i != path.end(); ++i)
		qDebug() << (*i)->x() << (*i)->y() << '\n';
}
コード例 #14
0
ファイル: main.cpp プロジェクト: jay602/a-star
int main()
{
	char maps[1000][1000] =
	{
		{ 0, 1, 0, 0, 0, 1, 0, 0, 0, 0 },
		{ 0, 0, 0, 1, 0, 1, 0, 1, 0, 1 },
		{ 1, 1, 1, 1, 0, 1, 0, 1, 0, 1 },
		{ 0, 0, 0, 1, 0, 0, 0, 1, 0, 1 },
		{ 0, 1, 0, 1, 1, 1, 1, 1, 0, 1 },
		{ 0, 1, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
		{ 0, 0, 0, 0, 1, 0, 0, 0, 1, 0 },
		{ 1, 1, 0, 0, 1, 0, 1, 0, 0, 0 },
		{ 0, 0, 0, 0, 0, 0, 1, 0, 1, 0 },
	};

	// 搜索参数
	AStar::Param param;
	param.width = 1000;
	param.height = 1000;
	param.allow_corner = false;
	param.start = AStar::Vec2(0, 0);
	param.end = AStar::Vec2(999, 999);
	param.is_canreach = [&](const AStar::Vec2 &pos)->bool
	{
		return maps[pos.y][pos.x] == 0;
	};

	// 执行搜索
	AStar as;
	Duration duration;
	auto path = as.search(param);

	std::cout << (path.empty() ? "路径未找到!" : "路径已找到!") << std::endl;
	std::cout << "本次寻路耗时" << duration.nano_seconds() << "纳秒" << std::endl;
	std::cout << '\n';
	system("pause");
	return 0;
}
コード例 #15
0
ファイル: Test.cpp プロジェクト: cd756819220/a-star-algorithm
int main(int argc, char *argv[])
{
	char maps[10][10] =
	{
		{ 0, 1, 0, 0, 0, 1, 0, 0, 0, 0 },
		{ 0, 0, 0, 1, 0, 1, 0, 1, 0, 1 },
		{ 1, 1, 1, 1, 0, 1, 0, 1, 0, 1 },
		{ 0, 0, 0, 1, 0, 0, 0, 1, 0, 1 },
		{ 0, 1, 0, 1, 1, 1, 1, 1, 0, 1 },
		{ 0, 1, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
		{ 0, 0, 0, 0, 1, 0, 0, 0, 1, 0 },
		{ 1, 1, 0, 0, 1, 0, 1, 0, 0, 0 },
		{ 0, 0, 0, 0, 0, 0, 1, 0, 1, 0 },
	};

	// 搜索参数
	AStar::Param param;
	param.width = 10;
	param.height = 10;
	param.corner = false;
	param.start = AStar::Vec2(0, 0);
	param.end = AStar::Vec2(9, 9);
	param.can_reach = [&](const AStar::Vec2 &pos)->bool
	{
		return maps[pos.y][pos.x] == 0;
	};

	// 执行搜索
	AStar as;
	Duration duration;
	auto path = as.find(param);
	std::cout << (path.empty() ? "路径未找到!" : "路径已找到!") << std::endl;
	std::cout << "本次寻路耗时" << duration.nano_seconds() << "纳秒" << std::endl;
	std::cout << '\n';

	return 0;
}
コード例 #16
0
ファイル: pathfind.cpp プロジェクト: kg/Fury2
F2FX int f2geAStarPathfind(f2gepathbuffer * pathbuffer, f2geblockbuffer * blocking, int startx, int starty, int endx, int endy) {
AStar * Pathfinder = new AStar;
POINT ptStart, ptEnd;
int nCopy = 0;
	ptStart.x = startx;
	ptStart.y = starty;
	ptEnd.x = endx;
	ptEnd.y = endy;
	Pathfinder->blocking = *blocking;
	if (Pathfinder->FindPath(ptStart, ptEnd)) {
		pathbuffer->path = (f2gepathpoint *)GlobalAlloc(GPTR, Pathfinder->nPath * 8);
		pathbuffer->size = Pathfinder->nPath;
		for (nCopy = 0; nCopy < pathbuffer->size; nCopy++) {
			pathbuffer->path[nCopy].x = Pathfinder->PATH[nCopy].x;
			pathbuffer->path[nCopy].y = Pathfinder->PATH[nCopy].y;
		}
		return true;
	} else {
		pathbuffer->path = (f2gepathpoint *)NULL;
		pathbuffer->size = 0;
		return false;
	}
}
コード例 #17
0
void MainWindow::on_pushButton_clicked() {

    AStar<Node> pathfinder;

    Node inicio(0, 0);
    Node fin(19, 19);

    inicio.setMap(this->ui->tableWidget);
    fin.setMap(this->ui->tableWidget);

    pathfinder.setBaseNode(inicio);
    pathfinder.setGoalNode(fin);

    cout << "Status: " << pathfinder.run() << endl;
    cout << "Pasos: " << pathfinder.getSteps() << endl;
    //pathfinder.showSolution();

    list<Node*> solution = pathfinder.solution();
    list<Node*>::iterator it;
    for (it = solution.begin(); it != solution.end(); it++) {
        ui->tableWidget->item((*it)->y, (*it)->x)->setBackgroundColor(QColor(255, 0, 0));
    }
}
コード例 #18
0
void Boss::move(int dir) {
    if (died) {
        return;
    }
    
    bool cancelCurrentPath = false;
    if (pathAStar != NULL) {
        // boss follow the path left.
        if (pathAStar->size() > 1) {
            Tile *currentTile = pathAStar->popBack();
            int nextRow = currentTile->row;
            int nextCol = currentTile->col;
            // if the next position is empty
            if (sim->board->validate(nextRow, nextCol) &&
                sim->board->getProp(nextRow, nextCol) == NULL &&
                sim->board->getUnit(nextRow, nextCol) == NULL) {
                sim->board->setUnit(row, col, NULL);
                sim->board->setUnit(nextRow, nextCol, this);
            }
            else {
                pathAStar->pushBack(currentTile);
                cancelCurrentPath = true;
            }
            
            if (!cancelCurrentPath) {
                return;
            }
        }
        
        delete pathAStar;
        pathAStar = NULL;
    }
    
    AStar *aStar = new AStar();
    
    DLLContainer<Tile *> *path = aStar->findPath(row, col, sim->board->getHero()->getRow(), sim->board->getHero()->getCol());
    delete aStar;
    if (path != NULL && path->size() > 2) {
        pathAStar = path;
        path->popBack(); // boss skip boss' position.
//        while (!path->isEmpty()) {
//            Tile *currentTile = path->popBack();
//            cout << "(" << currentTile->row << ", " << currentTile->col << ")->";
//        }
//        cout << endl;
//        sim->board->print();
//        exit(1);
        return;
    }
    
    if (path != NULL) {
        delete path;
    }
        
    // if hero is adjavcent then hit him.
    for (int i = row-1; i <= row+1; i++) {
        for (int j = col-1; j <= col+1; j++) {
            if (sim->board->validate(i, j) &&
                sim->board->getUnit(i, j) != NULL &&
                sim->board->getUnit(i, j)->isHero()) {
                sim->board->getUnit(i, j)->decHp(atk); // found! attak!!!
                return;
            }
        }
    }
        
    Monster::move(dir);
}
コード例 #19
0
int * PlaceJoueur::placeJoueur(int ** carte, int largeur,int hauteur, int* peuple, int nbJoueurs)
{

	vector< vector<Coordonnees> > tabZones;
	for(int i=0;i<nbJoueurs;i++)
	{
		vector<Coordonnees> tmp = findZone(carte,largeur,hauteur,peuple[i]);
		tabZones.push_back(tmp);
	}

	vector<Coordonnees> zoneAccessible = getUnion(tabZones);
	
	int * coord = new int[2*nbJoueurs];

	Coordonnees coordJ1, coordJ2;
	int max=0;
	
	AStar * star = new AStar();
	vector<Coordonnees>::iterator it = zoneAccessible.begin();
	for(;it!=zoneAccessible.end();it++)
	{
		vector<Coordonnees>::iterator it2 = zoneAccessible.begin();
		for(;it2!=zoneAccessible.end();it2++)
		{
			if (!(*it==*it2))
			{
				if (verif[peuple[0]][carte[(*it).x()][(*it).y()]])
				{
					vector<Node*>* res = star->pathFinding(tabToVecor(carte,largeur,hauteur),peuple[0],largeur,hauteur,(*it),(*it2));
					if (res->size()>max)
					{
						max=res->size();
						coordJ1 = (*it);
						coordJ2 = (*it2);
					}
				}
			}
		}
	}
	
	coord[0]=coordJ1.x();
	coord[1]=coordJ1.y();
	coord[2] = coordJ2.x();
	coord[3] = coordJ2.y();
	
	Coordonnees coordJ3;

	if (nbJoueurs>=3)
	{
		bool ok = false;
		int sigmaRef = 2;
		while (!ok)
		{
			double max=0;
			vector<Coordonnees>::iterator it = zoneAccessible.begin();
			for(;it!=zoneAccessible.end();it++)
			{
				if (!((*it) == coordJ1 || (*it) == coordJ2))
				{
					if (verif[peuple[2]][carte[(*it).x()][(*it).y()]])
					{
						vector<Node*>* res = star->pathFinding(tabToVecor(carte,largeur,hauteur),peuple[2],largeur,hauteur,(*it),(coordJ1));
						vector<Node*>* res2 = star->pathFinding(tabToVecor(carte,largeur,hauteur),peuple[2],largeur,hauteur,(*it),(coordJ2));
						if (std::abs((int)res->size()-(int)res2->size())<=2 && (res->size()+res2->size())/2>max)
						{
							max=(res->size()+res2->size())/2;
							coordJ3 = (*it);
							ok = true;
						}
					}
				}
			}
			sigmaRef++;
		}
		coord[4] = coordJ3.x();
		coord[5] = coordJ3.y();


		if (nbJoueurs==4)
		{
			Coordonnees coordJ4;
			bool ok = false;
			int sigmaRef = 3;
			while (!ok)
			{
				double max=0;
				vector<Coordonnees>::iterator it = zoneAccessible.begin();
				for(;it!=zoneAccessible.end();it++)
				{
					if (!((*it) == coordJ1 || (*it) == coordJ2 || (*it) == coordJ3))
					{
						if (verif[peuple[3]][carte[(*it).x()][(*it).y()]])
						{
							vector<Node*>* res = star->pathFinding(tabToVecor(carte,largeur,hauteur),peuple[3],largeur,hauteur,(*it),(coordJ1));
							vector<Node*>* res2 = star->pathFinding(tabToVecor(carte,largeur,hauteur),peuple[3],largeur,hauteur,(*it),(coordJ2));
							vector<Node*>* res3 = star->pathFinding(tabToVecor(carte,largeur,hauteur),peuple[3],largeur,hauteur,(*it),(coordJ3));
							int sigtmp1 = std::abs((int)res->size()-(int)res2->size());
							int sigtmp2 = std::abs((int)res2->size()-(int)res3->size());
							int sigtmp3 = std::abs((int)res->size()-(int)res3->size());
							if ((sigtmp1+sigtmp2+sigtmp3)/3<=sigmaRef && (res->size()+res2->size()+res3->size())/3>max)
							{
								max=(res->size()+res2->size()+res3->size())/3;
								coordJ4 = (*it);
								ok = true;
							}
						}
					}
				}
				sigmaRef++;
			}
			coord[6] = coordJ4.x();
			coord[7] = coordJ4.y();
		}
	}

	delete star;
	
	/*
	int nbJoueur = compteJoueurs(tabJoueurs,largeur,hauteur);

	srand (time(NULL));
	int * coord = new int[2];
	if (nbJoueur==0)
	{
		coord[0]=rand()%2*(largeur-1);
		coord[1]=rand()%2*(hauteur-1);
		int * coord2 = new int[2];
		coord2[0] = (((largeur-1)-coord[0])/4)*4;
		coord2[1] = (((hauteur-1)-coord[1])/4)*4;

		AStar * star = new AStar();
		vector<Node*>* res = star->pathFinding(tabToVecor(carte,largeur,hauteur),peuple,largeur,hauteur,Coordonnees(coord[0],coord[1]),Coordonnees(coord2[0],coord2[1]));
		delete star;
		coord[0]=res->back()->getCoord().x();
		coord[1]=res->back()->getCoord().y();
		delete res;

	}
	else if(nbJoueur==1)
	{
		coord = getCoordJoueur1(tabJoueurs,largeur,hauteur);
		int * coord2 = new int[2];
		coord2[0] = (((largeur-1)-coord[0])/4)*4;
		coord2[1] = (((hauteur-1)-coord[1])/4)*4;
		
		AStar * star = new AStar();
		vector<Node*>* res = star->pathFinding(tabToVecor(carte,largeur,hauteur),peuple,largeur,hauteur,Coordonnees(coord[0],coord[1]),Coordonnees(coord2[0],coord2[1]));
		delete star;
		coord[0]=res->back()->getCoord().x();
		coord[1]=res->back()->getCoord().y();
		delete res;

	}
	else
	{
		do
		{
			coord[0]=rand()%2*(largeur-1);
			coord[1]=rand()%2*(hauteur-1);
		} 
		while (tabJoueurs[coord[0]][coord[1]]!=0);
	}
	*/

	return coord;
}
コード例 #20
0
ファイル: prm.cpp プロジェクト: schvarcz/PRM
vector<Edge*> PRM::query(int numberClosestNeighbors)
{
    path.erase(path.begin(),path.end());
    struct timeval begin,end;
    gettimeofday(&begin,NULL);
    qDebug() << "Query começando";
    mGraph->V.push_back(mGoalNode);
    mGraph->V.push_back(mInitNode);


    vector<Node*> Nq = mInitNode->sortedClosest(mGraph,numberClosestNeighbors);
    Edge *edge = NULL;
    do
    {
        if(delta(mInitNode,Nq.at(0)) != NULL)
        {
            edge = new Edge(mInitNode,Nq.at(0));
            mInitNode->neighbors.push_back(edge);
            mGraph->E.push_back(edge);
        }
        else
        {
            Nq.erase(Nq.begin());
        }
    }while(Nq.size() && (edge == NULL));


    edge = NULL;
    Nq = mGoalNode->sortedClosest(mGraph,numberClosestNeighbors);
    do
    {
        if(delta(mGoalNode,Nq.at(0)) != NULL)
        {
            edge = new Edge(Nq.at(0),mGoalNode);
            Nq.at(0)->neighbors.push_back(edge);
            mGraph->E.push_back(edge);
        }
        else
        {
            Nq.erase(Nq.begin());
        }
    }while(Nq.size() && (edge == NULL));

    AStar search;
    bool again = false;
    do
    {
        again = false;
        path = search.shortestPath(mInitNode,mGoalNode); //Run shortest path
        for(int i=0;i<path.size();i++)
        {
            Edge *edge = path.at(i);
            if(!checkNodeAreaIsEmpty(edge->mNodeR))
            {
                qDebug() << "Removendo nodo ";
                Node *deletar = edge->mNodeR;
                for(int j=0;j<deletar->neighbors.size();j++)
                {
                    Edge *e = deletar->neighbors.at(j);
                    for(int x=0;x<e->mNodeR->neighbors.size();x++)
                    {
                        Edge *e2 = e->mNodeR->neighbors.at(x);
                        if(e2->mNodeR == deletar)
                        {
                            e->mNodeR->neighbors.erase(remove(e->mNodeR->neighbors.begin(),e->mNodeR->neighbors.end(),e2),e->mNodeR->neighbors.end());
                            mGraph->E.erase(std::remove(mGraph->E.begin(),mGraph->E.end(),e2),mGraph->E.end());
                            delete e2;
                        }
                    }
                    mGraph->E.erase(std::remove(mGraph->E.begin(),mGraph->E.end(),e),mGraph->E.end());
                    delete e;
                }
                mGraph->V.erase(std::remove(mGraph->V.begin(),mGraph->V.end(),deletar),mGraph->V.end());
                delete deletar;
                again = true;
                break;
            }
            if(delta(edge->mNodeL,edge->mNodeR) == NULL)
            {
                qDebug() << "Removendo arco ";
                Edge *deletar = edge;

                for(int j=0;j<deletar->mNodeR->neighbors.size();j++)
                {
                    Edge *e = deletar->mNodeR->neighbors.at(j);
                    if(e->mNodeR == deletar->mNodeL)
                    {
                        deletar->mNodeR->neighbors.erase(remove(deletar->mNodeR->neighbors.begin(),deletar->mNodeR->neighbors.end(),e),deletar->mNodeR->neighbors.end());
                        mGraph->E.erase(remove(mGraph->E.begin(),mGraph->E.end(),e),mGraph->E.end());
                        delete e;
                    }
                }
                for(int j=0;j<deletar->mNodeL->neighbors.size();j++)
                {
                    Edge *e = deletar->mNodeL->neighbors.at(j);
                    if(e->mNodeR == deletar->mNodeR)
                    {
                        deletar->mNodeL->neighbors.erase(remove(deletar->mNodeL->neighbors.begin(),deletar->mNodeL->neighbors.end(),e),deletar->mNodeL->neighbors.end());
                        mGraph->E.erase(remove(mGraph->E.begin(),mGraph->E.end(),e),mGraph->E.end());
                        delete e;
                    }
                }
                delete deletar;
                again = true;
                break;
            }
        }
    }while(again);

    if(path.size() == 0)
    {
        delete mInitNode;
        delete mGoalNode;
        mInitNode = mGoalNode = NULL;
    }

    Nq.at(0)->neighbors.pop_back();
    mGraph->E.pop_back();
    mGraph->E.pop_back();
    mGraph->V.pop_back();
    mGraph->V.pop_back();
    gettimeofday(&end,NULL);

    qDebug() << "Path achado!";
    qDebug() << "Tempo de query: " << ((double)(end.tv_usec-begin.tv_usec))/1000000 + (double)(end.tv_sec-begin.tv_sec);
    return path;
}
コード例 #21
0
ファイル: main.cpp プロジェクト: geediiiiky/astar
int main(int argc, const char * argv[])
{
    AStar astar;
    int rows = 20, columns = 20;
    Tiles env(rows, columns);
    random_device generator;
    uniform_int_distribution<int> distribution(1,20);
    
    vector<int> impassableNodes;
    for (int i = 0; i < columns * rows; i++)
    {
        int dice_roll = distribution(generator);
        if (dice_roll == 3)
        {
            impassableNodes.push_back(i);
        }
    }
    
    cout << "blocks(" << impassableNodes.size() << "): ";
    for (auto i : impassableNodes)
    {
        env.SetUntraverseable(i);
        cout << i << ", ";
    }
    cout << endl;

    
    
    std::uniform_int_distribution<int> startEndDistribution(0,rows * columns-1);
    int start, end;
    while (true) {
        start = startEndDistribution(generator);
        if (std::find(impassableNodes.begin(), impassableNodes.end(), start) == impassableNodes.end())
        {
            break;
        }
    }
    while (true) {
        end = startEndDistribution(generator);
        if (std::find(impassableNodes.begin(), impassableNodes.end(), end) == impassableNodes.end())
        {
            break;
        }
    }
    cout << "start = " << start << ", end  = " << end << ";" << endl;

    env.DrawMap(start, end);
    
    std::cout<<"-----------\n\n\n\n";
    
    astar.findPath(env, start, end);
//    astar.findPath(env, 11, 18);
    auto p = env.GetSmoothedPath(astar.getResultPath());
    
    for (auto n : p)
    {
        cout << n << ", ";
    }
    cout << endl;
    
    env.DrawSolution(p);
    return 0;
}