|
15鱼币
请问各位大佬们,我的回溯算法为什么会死循环?
- #include <stdio.h>
- const int step[8][2] = {{-1,-2},{1,-2},{-2,-1},{2,-1},{-1,2},{-2,1},{1,2},{2,1}};
- int array[8][8] = {0};
- int end(int (*array)[8]);
- int run(int row,int col,int (*array)[8])
- {
- int i;
- printf("%2d ",(row - 1) * 8 + col);
- if (end(array))
- {
- printf("success");
- return 1;
- }
- for (i = 0;i < 8;i++)
- {
- if (row + step[i][0] >= 1 && col + step[i][1] >= 1 && row + step[i][0] <= 8 && col + step[i][0] <= 8 && !array[row + step[i][0] - 1][col + step[i][1] - 1])
- {
- array[row + step[i][0] - 1][col + step[i][1] - 1] = (row + step[i][0] - 1) * 8 + (col + step[i][1]);
- run(row + step[i][0],col + step[i][1],array);
- printf("\b\b\b ");
- array[row + step[i][0] - 1][col + step[i][1] - 1] = 0;
- }
- }
- return 0;
- }
- int end(int (*array)[8])
- {
- for (int i = 0;i < 8;i++)
- {
- for (int j = 0;j < 8;j++)
- {
- if (!array[i][j])
- {
- return 0;
- }
- }
- }
- return 1;
- }
- int main(void)
- {
- int row,col;
- printf("请输入行数:");
- scanf("%d",&row);
- printf("请输入列数:");
- scanf("%d",&col);
- array[row - 1][col - 1] = (row - 1) * 8 + col;
- run(row,col,array);
-
- return 0;
- }
复制代码
你代码逻辑就是错的吧?
还有写代码不认真
- #include <stdio.h>
- const int step[8][2] = {{-1, -2}, {1, -2}, {-2, -1}, {2, -1}, {-1, 2}, {-2, 1}, {1, 2}, {2, 1}};
- int array[8][8] = {0};
- int end(int (*array)[8]);
- int run(int row, int col, int (*array)[8]) {
- int i;
- //printf("%2d ", (row - 1) * 8 + col);
- if(end(array)) {
- //printf("success");
- printf("success\n");
- return 1;
- }
- for(i = 0; i < 8; i++) {
- if(row + step[i][0] >= 1 && col + step[i][1] >= 1 &&
- // 认真一点
- //row + step[i][0] <= 8 && col + step[i][0] <= 8 &&
- row + step[i][0] <= 8 && col + step[i][1] <= 8 &&
- !array[row + step[i][0] - 1][col + step[i][1] - 1]) {
- array[row + step[i][0] - 1][col + step[i][1] - 1] =
- (row + step[i][0] - 1) * 8 + (col + step[i][1]);
- // 上面都减1,这里怎么不减1了?
- //run(row + step[i][0], col + step[i][1], array);
- run(row + step[i][0] - 1, col + step[i][1] - 1, array);
- //printf("\b\b\b ");
- array[row + step[i][0] - 1][col + step[i][1] - 1] = 0;
- }
- }
- return 0;
- }
- int end(int (*array)[8]) {
- for(int i = 0; i < 8; i++) {
- for(int j = 0; j < 8; j++) {
- if(!array[i][j]) {
- return 0;
- }
- }
- }
- return 1;
- }
- int main(void) {
- int row, col;
- printf("请输入行数:");
- scanf("%d", &row);
- printf("请输入列数:");
- scanf("%d", &col);
- // 这是在做什么?
- array[row - 1][col - 1] = (row - 1) * 8 + col;
- run(row, col, array);
- return 0;
- }
复制代码
|
|