PS/프로그래머스
[프로그래머스 - 12952] N-Queen
이세형
2020. 11. 3. 23:07
- 문제설명
- 풀이코드
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
|
#include <string>
#include <vector>
#include <iostream>
//https://programmers.co.kr/learn/courses/30/lessons/12952
using namespace std;
int answer;
bool can_queen(int y,int x, vector<pair<int,int>> &queens, int cnt){
for(int j=0;j<cnt;j++){
int y_2 = queens[j].first;
int x_2 = queens[j].second;
if( y==y_2 || x==x_2 ) return false;
if( abs(y-y_2) == abs(x-x_2) ) return false;
}
return true;
} void DFS(int n,int cnt,vector<pair<int,int>> &queens){
if(cnt == n){
answer++;
}else{
for(int i=0;i<n;i++){
int y = cnt;
int x = i;
int j = 0;
if(can_queen(y,x,queens,cnt)){
queens[cnt] = make_pair(y,x);
DFS(n,cnt+1,queens);
}
}
}
}
int solution(int n) {
vector<pair<int,int>> queens (n);
DFS(n,0,queens);
return answer;
}
|
cs |
- 시간복잡도
O(n^2)
- 남의 풀이와 비교
일반적인 다른 사람의 풀이와 비교했을 때 크게 차이없는 풀이 방식으로 풀었다.
첫번째 행에서 먼저 하나를 선택하고 다음행으로 가서 새로 선택한 것이 n-queen 조건에 만족하면 선택하고 아니면 선택하지 않는 방식으로 풀었다.
- Reference