#include<stdio.h> #include<stdlib.h> int sum = 0; int Danger(int r,int c, int(*a)[8]) { for(int i=0;i<8;i++) { if(a[i][c]) return 0; } for(int i=r,j=c;i>=0&&j>=0;i--,j--) { if(a[i][j]) return 0; } for(int i=r,j=c;i>=0&&j<8;i--,j++) { if(a[i][j]) return 0; } return 1; } /*int Danger(int row, int j, int(*chess)[8]){ int flag1 = 1, flag2 = 1, flag3 = 1, flag4 = 1, flag5 = 1; int ia, ib = 1, ic = 1, id = 1, ie = 1; for(ia = 0; ia < 8; ia++){ if(*(*(chess + ia) + j) == 1){ flag1 = 0; break; }else flag1 = 1; } while((row - ib) != -1 && (j - ib) != -1){ if(*(*(chess + row - ib) + j - ib) == 1){ flag2 = 0; break; }else flag2 = 1; ib++; } while((row + ic) != 8 && (j - ic) != -1){ if(*(*(chess + row + ic) + j - ic) == 1){ flag3 = 0; break; }else flag3 = 1; ic++; } while((row - id) != -1 && (j + id) != 8){ if(*(*(chess + row - id) + j + id) == 1){ flag4 = 0; }else flag4 = 1; id++; } while((row + ie) != 8 && (j + ie) != 8){ if(*(*(chess + row + ie) + j + ie) == 1){ flag5 = 0; break; }else flag5 = 1; ie++; } /* printf("%d", flag1); printf("%d", flag2); printf("%d", flag3); printf("%d", flag4); printf("%d", flag5); printf("\n");*/ //printf("/"); /* if(flag1 && flag2 && flag3 && flag4 && flag5){ return 1; }else return 0; } */ void EQ(int row, int col, int(*chess)[8]){ /* int chess[8][8]; for(int i = 0; i < 8; i++){ for(int j = 0; j < 8; j++){ chess[i][j] = pchess[i][j]; } }*/ if(row == 8){ for(int i = 0; i < 8; i++){ for(int j = 0; j < 8; j++){ printf("%d ", *(*(chess + i) + j)); } printf("\n"); } printf("\n"); ++sum; return; } for(int j = 0; j < 8; j++ ){ if(Danger(row, j, chess) == 1){ *(*(chess + row) + j) = 1; EQ(row + 1, col, chess); *(*(chess + row) + j) = 0; /* for(int i = 0; i < 8; i++){ *(*(chess + row ) + i) = 0; } continue;*/ } } } int main(){ int chess[8][8]; for(int i = 0; i < 8; i++){ for(int j = 0; j < 8; j++){ chess[i][j] = 0; } } EQ(0, 8, chess); printf("%d", sum); return 0; }
When the first code is implemented, the main logic is not considered clearly, and only output after one round of circulation. The problem is that there is no backtracking.
for(int j = 0; j < 8; j++ ){ if(Danger(row, j, chess) == 1){ *(*(chess + row) + j) = 1; EQ(row + 1, col, chess); *(*(chess + row) + j) = 0;
To flash back
Recurse to the last line. After the output is successful, the original position trace should be erased. Otherwise, it will affect the judgment of the Danger function
*(*(chess + row) + j) = 0;