'commit'
This commit is contained in:
45
C++专题课程/回溯算法/皇后问题(回溯法)/2N皇后_DFS解法.cpp
Normal file
45
C++专题课程/回溯算法/皇后问题(回溯法)/2N皇后_DFS解法.cpp
Normal file
@@ -0,0 +1,45 @@
|
||||
#include<bits/stdc++.h>
|
||||
using namespace std;
|
||||
// һ<><D2BB>һ<EFBFBD>е<EFBFBD>ö<EFBFBD>٣<EFBFBD><D9A3><EFBFBD>ö<EFBFBD>ٵ<EFBFBD>һ<EFBFBD>У<EFBFBD>Ȼ<EFBFBD><C8BB>ö<EFBFBD><C3B6>ÿһ<C3BF>У<EFBFBD><D0A3><EFBFBD>ö<EFBFBD>ٵ<EFBFBD><D9B5>е<EFBFBD>ʱ<EFBFBD><CAB1><EFBFBD><EFBFBD><EFBFBD>н<EFBFBD><D0BD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ѡ<EFBFBD>
|
||||
int n, cnt = 0, _map[10][10], vis[10][10];
|
||||
|
||||
bool check(int x, int y, int color) {
|
||||
int i, j;
|
||||
for (i = 1; i <= x; i++)
|
||||
if (vis[i][y] == color) return false;
|
||||
for (i = x, j = y; i > 0 && j > 0; i--, j--)
|
||||
if (vis[i][j] == color) return false;
|
||||
for (i = x, j = y; i > 0 && j <= n; i--, j++)
|
||||
if (vis[i][j] == color) return false;
|
||||
return true;
|
||||
}
|
||||
void dfs(int i) {
|
||||
int j, k;
|
||||
if (i > n) {
|
||||
cnt++;
|
||||
return;
|
||||
}
|
||||
for (j = 1; j <= n; j++) {
|
||||
if (_map[i][j] == 1 && check(i, j, 1)) {
|
||||
vis[i][j] = 1;
|
||||
for (k = 1; k <= n; k++) {
|
||||
if (j != k && _map[i][k] == 1 && check(i, k, -1)) {
|
||||
vis[i][k] = -1;
|
||||
dfs(i + 1);
|
||||
vis[i][k] = 0;
|
||||
}
|
||||
}
|
||||
vis[i][j] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
int main() {
|
||||
int i, j;
|
||||
cin >> n;
|
||||
for (i = 1; i <= n; i++)
|
||||
for (j = 1; j <= n; j++)
|
||||
cin >> _map[i][j];
|
||||
dfs(1);
|
||||
cout << cnt << endl;
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user