Hi, so I implemented this flood fill algorithm which works fine when the map is of size 96x96, but if I multiply this size by 2 (192x192) the algorithm becomes very slow and the game unplayable.
How can I optimize this algorithm for it to run faster?
The algorithm in question:
public void update(Node targetNode){
if(lastTargetNode.equals(targetNode)){
return;
}
lastTargetNode.set(targetNode.x, targetNode.y);
nodesToCalculateSize = 0;
targetNode.fScore = 0;
for(int i = 0; i < mapWidth; i++){
for(int j = 0; j < mapHeight; j++){
gradientMap[i][j] = 999999;
}
}
gradientMap[targetNode.y][targetNode.x] = 0;
neighboursAdded[targetNode.y][targetNode.x] = true;
nodesToCalculate[nodesToCalculateSize++] = targetNode;
while(nodesToCalculateSize > 0){
Node currentNode = nodesToCalculate[nodesToCalculateSize-- -1];
neighboursAdded[currentNode.y][currentNode.x] = false;
Node [] neighbours = getNeighbours(currentNode);
for(int i = 0; i < neighboursCount; i++){
if(gradientMap[neighbours[i].y][neighbours[i].x] == 999999) {
if(neighboursAdded[neighbours[i].y][neighbours[i].x] == false) {
nodesToCalculate[nodesToCalculateSize++] = neighbours[i];
neighboursAdded[neighbours[i].y][neighbours[i].x] = true;
}
gradientMap[neighbours[i].y][neighbours[i].x] = gradientMap[currentNode.y][currentNode.x] + 1;
}
}
}
}
Node [] getNeighbours(Node node){
neighboursCount = 0;
if(node.y - 1 >= 0)
if(mapCollisionMatrix[node.y - 1][node.x] == 0){
neighbours[neighboursCount] = nodes[node.y - 1][node.x];
neighboursCount++;
}
if(node.y + 1 < mapHeight)
if(mapCollisionMatrix[node.y + 1][node.x] == 0){
neighbours[neighboursCount] = nodes[node.y + 1][node.x];
neighboursCount++;
}
if(node.x - 1 >= 0)
if(mapCollisionMatrix[node.y][node.x - 1] == 0){
neighbours[neighboursCount] = nodes[node.y][node.x - 1];
neighboursCount++;
}
if(node.x + 1 < mapWidth)
if(mapCollisionMatrix[node.y][node.x + 1] == 0){
neighbours[neighboursCount] = nodes[node.y][node.x + 1];
neighboursCount++;
}
return neighbours;
}
Thanks in advance
EDIT: I removed ArrayList (Java) container and instead used an ordinary array and it improved the speed drastically.