为什么会死循环
查看原帖
为什么会死循环
555584
weiming3楼主2023/3/1 17:05
#include <iostream>
#include <cmath>
using namespace std;
int main() {
	void execute(int a[1105][1105], int r1, int c1, int r2, int c2, int r3, int c3,
	             int r4,
	             int c4);
	int n;
	cin >> n;
	int a[1105][1105];
	for (int i = 1; i <= pow(2, n); i++) {
		for (int j = 1; j <= pow(2, n); j++) {
			a[i][j] = 1;
		}
	}
	execute(a, 1, 1, 1, pow(2, n), pow(2, n), 1, pow(2, n), pow(2, n));
	for (int i = 1; i <= pow(2, n); i++) {
		for (int j = 1; j <= pow(2, n); j++) {
			cout << a[i][j] << " ";
		}
		cout << endl;
	}
	return 0;
}
void execute(int  a[1105][1105], int r1, int c1, int r2, int c2, int r3, int c3,
             int r4,
             int c4) {
	if (r1 == 1 && c1 == 1) {
		for (int i = 1; i <= r3 / 2; i++) {
			for (int j = 1; j <= c2 / 2; j++) {
				a[i][j] = 0;
			}
		}
	} else	if (c1 == c2) {
		return;
	} else {
		execute(a, r1, (c1 + c2) / 2 + 1, r2, c2, (r1 + r3) / 2 - 1, (c1 + c2) / 2 + 1,
		        (r1 + r3) / 2 - 1, c4);
		execute(a, (r1 + r3) / 2 + 1, c1, (r1 + r3) / 2 + 1, (c1 + c2) / 2 - 1, r3, c3,
		        r4, (c1 + c2) / 2 - 1);
		execute(a, (r1 + r3) / 2 + 1, (c1 + c2) / 2 + 1, r2, (c1 + c2) / 2 + 1,
		        (r1 + r3) / 2 + 1, c3, r4, c4);
	}
}

来自chatgpt There is another potential issue with the execute function. In the second recursive call to execute, the condition to stop the recursion is when c1 == c2. However, since c2 is not being updated in that recursive call, it's possible for the condition to never be met and for the function to continue recursing indefinitely, leading to a stack overflow or other errors.

To fix this, you should update c2 in the second recursive call to execute so that it converges towards the base case where c1 == c2. For example, you could replace (r1 + r3) / 2 + 1, (c1 + c2) / 2 - 1 with (r1 + r3) / 2 + 1, c2 - (c2 - c1 + 1) / 2 in the second recursive call.

2023/3/1 17:05
加载中...