C++ 为什么我的代码显示分段错误?
我的代码如下。它是给分割错误。我一直在调试它,但卡住了!我找不到问题。有人能帮我吗C++ 为什么我的代码显示分段错误?,c++,algorithm,segmentation-fault,flood-fill,C++,Algorithm,Segmentation Fault,Flood Fill,我的代码如下。它是给分割错误。我一直在调试它,但卡住了!我找不到问题。有人能帮我吗 #include <iostream> #include <fstream> using namespace std; char art[200][200]; char art2[200][200]; int n; void solve(char a, int x, int y); int main() { // ifstream fin("cowart.in");
#include <iostream>
#include <fstream>
using namespace std;
char art[200][200];
char art2[200][200];
int n;
void solve(char a, int x, int y);
int main() {
// ifstream fin("cowart.in");
// ofstream fout("cowart.out");
cin >> n;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
cin >> art[i][j];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
art2[i][j] = art[i][j];
int rh = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (art[i][j] == 'R' || art[i][j] == 'G' || art[i][j] == 'B') {
rh++;
solve(art[i][j], i, j);
}
}
}
int rc = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
art[i][j] = art2[i][j];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if (art[i][j] == 'G')
art[i][j] = 'R';
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (art[i][j] == 'R' || art[i][j] == 'B') {
rc++;
solve(art[i][j], i, j);
}
}
}
cout << rh << " " << rc << endl;
// system("PAUSE");
// fin.close();
// fout.close();
return 0;
}
void solve(char a, int x, int y) {
if (x < 0 || y < 0 || x >= n || y >= n)
return;
if (art[x][y] != a)
return;
art[x][y] == '.';
if (x < n - 1)
solve(a, x + 1, y);
if (x > 0)
solve(a, x - 1, y);
if (y < n - 1)
solve(a, x, y + 1);
if (y > 0)
solve(a, x, y - 1);
return;
}
输出应该是:43
在solve()
函数中,注意这一行吗
art[x][y] == '.';
上面的代码测试art[x][y]
是否等于。
,然后丢弃结果。它是合法的C++,但没有任何用处。智能编译器可能会给您一个警告
这显然是一项任务:
art[x][y] = '.';
函数solve()进行无限递归,导致堆栈溢出。
使用非递归而非迭代方法实现求解。
通过循环和迭代以迭代方式实现4-邻域问题谢谢!它现在可以工作,并提供AC:)
art[x][y] = '.';