使用靜態數組模擬隊列,避免 STL queue 開銷,邏輯完全相同。
struct Node { int x, y, z; };
Node q[30*30*30];
int head = 0, tail = 0;
void push(Node n) { q[tail++] = n; }
Node pop() { return q[head++]; }
bool empty() { return head == tail; }
// BFS 主循環
push({sx, sy, sz});
map[sz][sy][sx] = '#';
int dist[35][35][35] = {0};
while (!empty()) {
Node cur = pop();
if (cur.x == ex && cur.y == ey && cur.z == ez) return dist[cur.z][cur.y][cur.x];
for (int i = 0; i < 6; ++i) {
int nx = cur.x + dx[i], ny = cur.y + dy[i], nz = cur.z + dz[i];
if (in_bounds && map[nz][ny][nx] != '#') {
map[nz][ny][nx] = '#';
dist[nz][ny][nx] = dist[cur.z][cur.y][cur.x] + 1;
push({nx, ny, nz});
}
}
}
queue 已高度優化,差異可忽略。