- 八皇后问题是一个经典的问题:在一个8*8的国际象棋盘中,摆放8个皇后,使得任意两个皇后不能互相伤害。这就要求任意两个皇后不能在同一行、同一列、同一对角线。
- 这个问题可以使用深搜来解决:
一行一行找能摆放的位置,board[i][j] = 1 表示在(i, j)这个位置摆放了皇后
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
|
#include <iostream> #include <cmath>
using namespace std; const int n = 8; int board[n][n]; int tot = 0;
int valid(int x, int y) { for (int i = 0; i < x; i++) { if (board[i][y] == 1) return 0; } for (int i = 0; i < x; i++) { for (int j = 0; j < n; j++) { if (board[i][j] == 1 && (abs(i - x) == abs(j - y))) { return 0; } } } return 1; }
void dfs(int x) { if (x == n) { tot++; return; } for (int i = 0; i < n; i++) { if (valid(x, i)) { board[x][i] = 1; dfs(x + 1); board[x][i] = 0; } } }
int main() { dfs(0); cout << tot << endl; return 0; }
|
扩展到n皇后,在暂时不优化深搜时间的同时,这个解法的空间复杂度是n^2, 事实上,如果令 board[i] = j 表示第i行第j列放置了皇后,那么可以把上面的矩阵压缩成一维。
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
|
#include <iostream> #include <cmath>
using namespace std; const int n = 8; int board[n]; int tot = 0;
int valid(int x, int y) { for (int i = 0; i < x; i++) { if (board[i] == y || abs(i - x) == abs(board[i] - y)) return 0; } return 1; }
void dfs(int x) { if (x == n) { tot++; return; } for (int i = 0; i < n; i++) { if (valid(x, i)) { board[x] = i; dfs(x + 1); } } }
int main() { dfs(0); cout << tot << endl; return 0; }
|