I have a flood fill function in my code that just returns a number on the cells filled. But it is excruciatingly slow, my A* pathfinding algorithm is exponentially faster than it. Here is the snippet:
bool withinBoundaries(_2D::Point p) {
//cerr << "Checking if x: " << p.x << " y: " << p.y << " is within boundaries" << endl;
if (p.x <= 29 && p.y <= 19 && p.x >= 0 && p.y >= 0) {
return true;
}
return false;
}
bool canMove(_2D::Point point, _2D::Point offset, map<pair<int, int>, bool> gameGrid) {
if (!gameGrid[(point + offset).toPair()] && withinBoundaries(point + offset)) return true;
else return false;
}
int floodFillGetArea(_2D::Point point, map<pair<int, int>, bool> gameGrid) {
map<pair<int, int>, bool> checked;
map<pair<int, int>, bool> gameGridCopy = gameGrid;
deque<_2D::Point> openPoints;
openPoints.push_back(point);
int count = 0;
while (!openPoints.empty()) {
_2D::Point curPoint = openPoints.back();
openPoints.pop_back();
if(checked[curPoint.toPair()]) break;
gameGridCopy[curPoint.toPair()] = true;
count++;
if (canMove(curPoint, _2D::Point::UP(), gameGridCopy)) {
openPoints.push_back(curPoint + _2D::Point::UP());
}
if (canMove(curPoint, _2D::Point::RIGHT(), gameGridCopy)) {
openPoints.push_back(curPoint + _2D::Point::RIGHT());
}
if (canMove(curPoint, _2D::Point::DOWN(), gameGridCopy)) {
openPoints.push_back(curPoint + _2D::Point::DOWN());
}
if (canMove(curPoint, _2D::Point::LEFT(), gameGridCopy)) {
openPoints.push_back(curPoint + _2D::Point::LEFT());
}
checked[curPoint.toPair()] = true;
}
return count;
}
This checks a node every second, why is it so slow? And _2D::Point is just an object with int x and int y. Also it creates open nods when they are already labelled as being checked, why?