有关队列内存超限问题bfs()(待解决)
超限代码:
queue<node> arr;
node fir{ 0,0,0 };
arr.push(fir);
int ex = x - 1, ey = y - 1, ez = z - 1;
visit[0][0][0] = 1;
int node1 = 1, k = 0;
while (!arr.empty() && arr.front().x != ex || arr.front().y != ey || arr.front().z != ez)
{
k++;
int num = 0;
for (int n = 0; n < node1; n++)
{
if (arr.front().x == ex && arr.front().y == ey && arr.front().z == ez)
{
while (!arr.empty()) arr.pop(); break;
}
// 不是目标,进行标记
visit[arr.front().x][arr.front().y][arr.front().z] = 1;
for (int i = 0; i < 6; i++)
{
node temp{};
int tx = arr.front().x + next[i][0],
ty = arr.front().y + next[i][1],
tz = arr.front().z + next[i][2];
// 下标在数组范围内
// 迷宫中为路
// 未标记过的有效点
if (visit[tx][ty][tz] == 0
&& tx < x && tx >= 0
&& ty < y && ty >= 0
&& tz < z && tz >= 0
&& map[tx][ty][tz] == 0)
{
temp.x = tx;
temp.y = ty;
temp.z = tz;
// 更新最短路
cout << k << " " << len[temp.x][temp.y][temp.z] << endl;
len[temp.x][temp.y][temp.z] = min(len[temp.x][temp.y][temp.z], k);
cout << k<<" " << len[temp.x][temp.y][temp.z] << endl;
//加入有效点
arr.push(temp);
// 统计有效节点
num++;
}
}
// 弹出队列首元素
arr.pop();
}
node1 = num;
}
if (len[ex][ey][ez] == inf) cout << -1 << endl;
else cout << len[ex][ey][ez] << endl;
}
不超限代码:
void bfs()
{
queue<node> arr;
node fir{ 0,0,0,0 };
arr.push(fir);
int ex = x - 1, ey = y - 1, ez = z - 1;
visit[0][0][0] = 1;
int node1 = 1, k = 0;
while (!arr.empty())
{
int num = 0;
if (arr.front().x == ex && arr.front().y == ey && arr.front().z == ez)
{
if (arr.front().val <= T)
cout << arr.front().val << endl;
else
cout << -1 << endl;
return;
}
for (int i = 0; i < 6; i++)
{
node temp{};
int tx = arr.front().x + next1[i][0],
ty = arr.front().y + next1[i][1],
tz = arr.front().z + next1[i][2];
// 下标在数组范围内
// 迷宫中为路
// 未标记过的有效点
if (visit[tx][ty][tz] == 0
&& tx < x && tx >= 0
&& ty < y && ty >= 0
&& tz < z && tz >= 0
&& map[tx][ty][tz] == 0)
{
temp.x = tx;
temp.y = ty;
temp.z = tz;
// 更新最短路(以上一级为参考)
temp.val = arr.front().val + 1;
// 不是目标,进行标记
visit[tx][ty][tz] = 1;
//加入有效点
arr.push(temp);
}
}
// 弹出队列首元素
arr.pop();
}
cout << -1 << endl;
return;
}