코딩/BOJ & 알고스팟
[BOJ 9663] N-Queen
hoon222y
2017. 10. 4. 15:39
https://www.acmicpc.net/problem/9663
백트레깅 너무 어렵당. 백트레킹과 완전탐색의 차이라고 한다면 alpha beta pruning 처럼 백트레킹에는 커팅되는 과정이 추가된다고 생각할수 있을꺼 같다 (뇌피셜 ) 모든 경우를 다해보지 않고 일단 각 행에는 1개씩은 queen이 존재할 수 있으므로 모든행까지 다 가는 경우는 완성할 수 있는 경우의 수가 +1이 된다.
각각의 배열 3개를 통해서 해당 퀸이 같은 열이 있는지, 같은 대각선 1,2에 있는지를 상수시간에 확인할 수 있다. 어렵당
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 46 47 48 49 50 51 | #include <iostream> #include <cstdio> #include <vector> #include <cmath> #include <algorithm> #include <cstring> #include <set> #include <queue> typedef long long ll; using namespace std; int n,arrCol[55],arrDe1[55],arrDe2[55],ans; bool chk(int y,int x){ if(arrCol[x] == 1) return false; if(arrDe1[y+x] == 1) return false; if(arrDe2[n+y-x] == 1) return false; return true; } void solve(int c){ if(c == n){ ans++; return; } for(int i=0;i<n;i++){ if(chk(c,i)){ arrCol[i] = 1; arrDe1[c+i] = 1; arrDe2[n+c-i] = 1; solve(c+1); arrCol[i] = 0; arrDe1[c+i] = 0; arrDe2[n+c-i] = 0; } } } int main(){ ans = 0; scanf("%d" , &n); solve(0); cout <<ans <<endl; return 0; } | cs |