我认为你做的一切都是正确的。如果编码正确,则需要 O(n) 时间和 O(n) 内存来计算洪水填充,其中 n 是单元数,并且可以证明不可能做得更好(在一般情况下)。填充完成后,您只需返回任何目的地的距离 O(1),很容易看出它也可以做得更好。
所以如果你想优化性能,你只能专注于代码本地优化。这不会影响渐近,但可以显着提高您的实际执行时间。但是如果没有真正看到源代码,很难给你任何代码优化建议。
因此,如果您真的想查看优化代码,请参阅以下(纯 C):
包括
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));
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);
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 * leadDim + Y;
map[X * leadDim + Y] = 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;
}
代码可能看起来很棘手。当然,它看起来不像 OOP(我实际上认为 OOP 粉丝会讨厌它),但如果你想要一些非常快的东西,那就是你需要的。