I think you have done everything right. If you coded it correct it takes O(n)
time and O(n)
memory to compute flood fill, where n
is the number of cells, and it can be proven that it's impossible to do better (in the general case). And after the fill is complete you just return the distance for any destination with O(1)
, it is easy to see that it also can be done better.
So if you want to optimize performance, you can only focus on code local optimization. This will not affect the asymptotic complexity but can significantly improve your real execution time. But it's hard to give you any advice for code optimization without actually seeing the source code.
So if you really want to see optimized code see the following (Pure C):
#include <stdlib.h>
int* BFS()
{
int N, M; // Assume we have NxM grid.
int X, Y; // Start position. X, Y are unit based.
int i, j;
int movex[4] = {0, 0, 1, -1}; // Move on x dimension.
int movey[4] = {1, -1, 0, 0}; // Move on y dimension.
// TO DO: Read N, M, X, Y
// To reduce redundant functions calls and memory reallocation
// allocate all needed memory once and use a simple arrays.
int* map = (int*)malloc((N + 2) * (M + 2) * sizeof(int));
int leadDim = M + 2;
// Our map. We use one dimension array. map[x][y] = map[leadDim * x + y];
// If (x,y) is occupied then map[leadDim*x + y] = -1;
// If (x,y) is not visited map[leadDim*x + y] = -2;
int* queue = (int*)malloc(N * M * sizeof(int));
int first = 0, last =1;
// Fill the boarders to simplify the code and reduce conditions
for (i = 0; i < N+2; ++i)
{
map[i * leadDim + 0] = -1;
map[i * leadDim + M + 1] = -1;
}
for (j = 0; j < M+2; ++j)
{
map[j] = -1;
map[(N + 1) * leadDim + j] = -1;
}
// TO DO: Read the map.
queue[first] = (X+1) * leadDim + Y + 1;
map[(X+1) * leadDim + Y + 1] = 0;
// Very simple optimized process loop.
while (first < last)
{
int current = queue[first];
int step = map[current];
for (i = 0; i < 4; ++i)
{
int temp = current + movex[i] * leadDim + movey[i];
if (map[temp] == -2) // only one condition in internal loop.
{
map[temp] = step + 1;
queue[last++] = temp;
}
}
++first;
}
free(queue);
return map;
}
The code may seem tricky. And of course, it is not object oriented (OOP) but if you want something really fast that's what you need.