#include <iostream> #include <iomanip> using namespace std; #define N 6 int a[N][N] = { 0 }; bool judge(int a[][N], int b, int c, int dir) { if (dir == 0) { if (b - 2 >= 0 && c - 1 >= 0 && a[b - 2][c - 1] == 0) { return true; } else { return false; } } if (dir == 1) { if (b - 1 >= 0 && c - 2 >= 0 && a[b - 1][c - 2] == 0) { return true; } else { return false; } } if (dir == 2) { if (b - 2 >= 0 && c + 1 <= N-1 && a[b - 2][c + 1] == 0) { return true; } else { return false; } } if (dir == 3) { if (b - 1 >= 0 && c + 2 <= N-1 && a[b - 1][c + 2] == 0) { return true; } else { return false; } } if (dir == 4) { if (b + 2 <= N-1 && c - 1 >= 0 && a[b + 2][c - 1] == 0) { return true; } else { return false; } } if (dir == 5) { if (b + 1 <= N-1 && c - 2 >= 0 && a[b + 1][c - 2] == 0) { return true; } else { return false; } } if (dir == 6) { if (b + 2 <= N-1 && c + 1 <= N-1 && a[b + 2][c + 1] == 0) { return true; } else { return false; } } if (dir == 7) { //cout << "dir = 7 "; if (b + 1 <= N-1 && c + 2 <= N-1 && a[b + 1][c + 2] == 0) { return true; } else { return false; } } } void print() { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { cout << setw(5) << a[i][j] ; } cout << endl; } } int count1 = 1; int count2 = 1; void fun(int a[][N],int b,int c) { if (count1 == N*N ) { print(); cout << "方案:" << count2++ << endl; cout << endl; system("pause"); } else { for (int i = 0; i < 8; i++) { if (judge(a, b, c, i)) { switch (i) { case 0: count1++; a[b - 2][c - 1] = count1; fun(a, b - 2, c - 1); a[b - 2][c - 1] = 0; count1--; break; case 1: count1++; a[b - 1][c - 2] = count1; fun(a, b - 1, c - 2); a[b - 1][c - 2] = 0; count1--; break; case 2: count1++; a[b - 2][c + 1] = count1; fun(a, b - 2, c + 1); a[b - 2][c + 1] = 0; count1--; break; case 3: count1++; a[b - 1][c + 2] = count1; fun(a, b - 1, c + 2); a[b - 1][c + 2] = 0; count1--; break; case 4: count1++; a[b + 2][c - 1] = count1; fun(a, b + 2, c - 1); a[b + 2][c - 1] = 0; count1--; break; case 5: count1++; a[b + 1][c - 2] = count1; fun(a, b + 1, c - 2); a[b + 1][c - 2] = 0; count1--; break; case 6: count1++; a[b + 2][c + 1] = count1; fun(a, b + 2, c + 1); a[b + 2][c + 1] = 0; count1--; break; case 7: count1++; a[b + 1][c + 2] = count1; fun(a, b + 1, c + 2); a[b + 1][c + 2] = 0; count1--; break; } } } } } void main() { a[2][0] = 1; fun(a, 2, 0); system("pause"); }