1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| #include<iostream> #include<vector> using namespace std; int dir_x[8] = { -1, -1, -1, 1, 1, 1, 0, 0 }; int dir_y[8] = { 0 , 1, -1, 0, 1,-1, 1,-1 }; void copy_attack(int(*attack)[8], int(*temp)[8]); void update_attack(int(*attack)[8], int i, int k); void ini_att_que(int (*attack)[8], char (*queen)[8]); void backtrack(int n, int(*attack)[8], char(*queen)[8]); int counts; int main() { int attack[8][8]; char queen[8][8]; ini_att_que(attack, queen); backtrack(0, attack, queen); cout << "八皇后问题一共有" << counts << "种解法。" << endl; return 0; } void ini_att_que(int (*attack)[8], char (*queen)[8]) { for (int i = 0; i < 64; i++) *(*attack + i) = 0; for (int i = 0; i < 64; i++) *(*queen + i) = '#'; } void backtrack(int n, int(*attack)[8], char(*queen)[8]) { if (n == 8) { for (int i = 0; i < 8; i++) { for (int k = 0; k < 8; k++) printf("% c ", queen[i][k]); cout << endl; } printf("=====================================\n"); counts++; return; } for (int col = 0; col < 8; col++) { if (attack[n][col] == 0) { int temp[8][8]; copy_attack(attack,temp); queen[n][col] = 'Q'; update_attack(attack, n, col); backtrack(n + 1, attack, queen); copy_attack(temp, attack); queen[n][col] = '#'; } } } void copy_attack(int(*attack)[8],int(*temp)[8]) { for (int i = 0; i < 8; i++) { for (int k = 0; k < 8; k++) temp[i][k] = attack[i][k]; } } void update_attack(int(*attack)[8],int i,int k) { for (int m = 1; m < 8; m++) { for (int g = 0; g < 8; g++) { int nx = i + m * dir_x[g]; int ny = k + m * dir_y[g]; if (nx >= 0 && nx < 8 && ny >= 0 && ny < 8) { attack[nx][ny] = 1; } } } }
|