백준알고리즘
N-Queen
먼지의삶
2019. 10. 9. 22:56
https://www.acmicpc.net/problem/9663
9663번: N-Queen
N-Queen 문제는 크기가 N × N인 체스판 위에 퀸 N개를 서로 공격할 수 없게 놓는 문제이다. N이 주어졌을 때, 퀸을 놓는 방법의 수를 구하는 프로그램을 작성하시오.
www.acmicpc.net
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
|
#include<iostream>
using namespace std;
int n,ans;
bool r[32];
bool c[32];
bool row[16];
bool col[16];
void Queen(int y, int cnt) {
if (cnt == n) {
ans++;
return;
}
for (int i = 0; i < n; i++) {
if (row[i] == false && col[y] == false && r[i + y] == false && c[i - y + (n-1)] == false) {
row[i] = true;
col[y] = true;
r[i + y] = true;
c[i - y + (n-1)] = true;
Queen(y + 1, cnt + 1);
row[i] = false;
col[y] = false;
r[i + y] = false;
c[i - y + (n - 1)] = false;
}
}
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n;
Queen(0, 0);
cout << ans << '\n';
return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
백트래킹 복습으로 다시해본 N-Queen 문제
row col, 그리고 대각선을 기준으로 검증해줘서 재귀를돌린 모형으로했다.
기존의것보다 조금더 빠름