일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- Python
- Fast API
- 백준
- dockerfile
- AWS
- 알고리즘
- Kubernetes
- docker
- 동시성
- Container
- 플랫폼
- guru
- fluent python
- BAEKJOON
- 이더리움
- function
- 파이썬
- Ethereum
- Network
- BlockChain
- 코어 이더리움 프로그래밍
- RabbitMQ
- IMAGE
- 전문가를 위한 파이썬
- Thread
- Algorithm
- rust
- 블록체인
- 러스트
- Refactoring
Archives
- Today
- Total
글쓰기 | 방명록 | 관리 |
Victoree's Blog
9663_N-Queen 본문
728x90
Concept & Idea
돌아가는 포문의 i는 col을 의미한다. map[i]의 값은 배치된 queen의 행값이다. isPossible 함수에서 같은 열에 위치되있거나 대각선방향에 있을 경우, 다음 위치로 이동하지 않는다. 처음엔 map[15][15]라는 배열을 만들었는데, 그렇게 푸는 것이 아니라 내가 있는 위치를 기록함으로써 메모리를 줄일 수 있었다.
Code
#include <iostream>
using namespace std;
int n,map[16];
int res=0;
bool isPossible(int x){
for(int i=1; i<x; i++) {
if(map[x]==map[i] || abs(x-i) == abs(map[x]-map[i])) {
return false;
}
}
return true;
}
void dfs(int x){
if(x==n) {
res++;
return;
}
for(int i=1; i<=n; i++) {
map[x+1]=i;
if(isPossible(x+1)) {
dfs(x+1);
}
map[x+1] = 0;
}
}
int main() {
cin>>n;
for(int i=1; i<=n; i++) {
map[1]=i;
dfs(1);
map[1]=0;
}
cout<<res<<endl;
}
Fealing
너무 오랜만에 풀어낸 알고리즘 문제라서 머리가 너무 잘 안돌아갔다..
728x90
Comments