https://www.acmicpc.net/problem/9663
백트래킹에서 유명한 N-Queen문제이다.
dfs를 통해 말이 일직선상에 있거나 대각선에 있는지를 확인해준다.
만약에 있다면 더이상 진행하지 않고 없다면 N번째까지 진행해주면 된다.
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 | #include <iostream> #include <math.h> using namespace std; int N; int ans=0; int queen[16]={0}; bool promising(int n){ for(int i=1;i<n;i++){ if(queen[n]==queen[i] || n-i==abs(queen[n]-queen[i])) return false; } return true; } void dfs(int n){ if(n==N+1){ ans++; return; } for(int i=1;i<=N;i++){ queen[n]=i; if(promising(n)){ dfs(n+1); } } } int main(){ cin>>N; dfs(1); cout<<ans<<endl; return 0; } | cs |
'알고리즘(BOJ) > 백트래킹' 카테고리의 다른 글
백준 2210번 - 숫자판 점프 (0) | 2019.08.30 |
---|---|
백준 9207번 - 페그 솔리테어 (0) | 2019.04.13 |
백준 1339번 - 단어 수학 (0) | 2019.03.30 |
백준 2023번 - 신기한 소수 (0) | 2019.03.29 |