這種題目乍一看屬於讀懂了,就會做的類型,只要注意下不要使用遞歸就可以,但在做的過程中第五個測試點一直過不了,百思不得其解,後來敲了一遍別人的答案,才發現是容器上的一個問題。柳神的參考代碼鏈接
我自己的實現
using namespace std;
int m, n, l, t, vol = 0;
int matrix[70][1300][130];
bool visited[70][1300][130];
int x[] = {0, 0, 0, 0, 1, -1};
int y[] = {0, 0, 1, -1, 0, 0};
int z[] = {1, -1, 0, 0, 0, 0};
struct node {
int x, y, z;
node() = default;
node(int x, int y, int z) : x(x), y(y), z(z) {}
};
void BFS(int i, int j, int k) {
visited[i][j][k] = true;
queue<node> q;
int n_x, n_y, n_z;
q.emplace(i, j, k);
int cnt = 0;
while (!q.empty()) {
++cnt;
auto &e = q.front();
for (int i1 = 0; i1 < 6; ++i1) {
n_x = e.x + x[i1];
n_y = e.y + y[i1];
n_z = e.z + z[i1];
if (n_x >= 0 && n_x < l && n_y >= 0 && n_y < m && n_z >= 0 && n_z < n &&
matrix[n_x][n_y][n_z] == 1 && !visited[n_x][n_y][n_z]) {
q.emplace(n_x, n_y, n_z);
visited[n_x][n_y][n_z] = true;
}
}
q.pop();
}
if (cnt >= t) vol += cnt;
}
在BFS的過程我們頻繁使用隊列進出操作,如下是一些常見的操作
auto e = q.front(); // ok 這種操作需要調用拷貝函數,如果數據量大可能會被卡時間,
q.pop();
// do something
auto &e = q.front(); // 題目中這種操作使得第五個點沒過,我也不清楚是爲什麼,但是以後儘量避免此類操作
q.pop();
// do something
auto &e = q.front(); // ok 結合效率和正確性的操作,但容器只能爲隊列,在棧中不能這樣操作,中間代碼可能又添加新的元素到棧頂
// do something
q.pop();