#include <iostream>
#include <queue>
#define maxn 35
using namespace std;
int n;
int arr[maxn][maxn];
bool vis[maxn][maxn];
struct pr {
int h, l;
pr() {}
pr(int a, int b) {
l = a;
h = b;
}
} a[1000000];
void bfs() {
int k = 0;
queue<pr> que;
pr st;
for (int i = 2; i <= n - 1; i++) {
for (int j = 2; j <= n - 1; j++) {
if (arr[i][j] == 0 && !vis[i][j]) {
st.l = i;
st.h = j;
}
}
}
que.push(st);
while (!que.empty()) {
st = que.front();
que.pop();
vis[st.l][st.h] = true;
if (arr[st.l][st.h] == 0) {
a[k++] = st;
if (!vis[st.l - 1][st.h]) {
que.push(pr(st.l - 1, st.h));
}
if (!vis[st.l + 1][st.h]) {
que.push(pr(st.l + 1, st.h));
}
if (!vis[st.l][st.h - 1]) {
que.push(pr(st.l, st.h - 1));
}
if (!vis[st.l][st.h + 1]) {
que.push(pr(st.l, st.h + 1));
}
} else if (arr[st.l][st.h] == 3) {
k = 0;
while (!que.empty()) {
que.pop();
}
for (int i = 2; i <= n - 1; i++) {
for (int j = 2; j <= n - 1; j++) {
if (arr[i][j] == 0 && !vis[i][j]) {
st.l = i;
st.h = j;
}
}
}
que.push(st);
}
}
for (int i = 0; i < k; i++) {
arr[a[i].l][a[i].h] = 2;
}
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cin >> arr[i][j];
}
}
for (int i = 0; i <= n + 1; i++) {
arr[0][i] = arr[n + 1][i] = arr[i][0] = arr[i][n + 1] = 3;
}
bfs();
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
return 0;
}C++的:exit code -1073741819 (0xC0000005) 怎么解决?
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
1条回答 默认 最新
幻灰龙 2021-02-16 22:40关注下面这段代码for循环的条件不满足时,for循环并没有执行,st并没有被初始化,于是你push进去后后面的代码取出来使用时,st.h和st.l是随机数据,超出vist的容量时数组越界,程序崩溃。
pr st; for (int i = 2; i <= n - 1; i++) { for (int j = 2; j <= n - 1; j++) { if (arr[i][j] == 0 && !vis[i][j]) { st.l = i; st.h = j; } } } que.push(st);这种问题,问题不在于代码错在哪里,而在于需要把代码切割成更小的小函数,针对每个小函数单独进行单元测试,每个函数经过单元测试都功能正确后再组装起来完成更复杂的功能。这样层层编程才能实现可测试、可调试、可快速诊断问题在哪里的好的程序。
本回答被题主选为最佳回答 , 对您是否有帮助呢?评论 打赏 举报解决 10无用 1