티스토리 뷰
728x90
문제
자연수 n을 입력받음
n*n 체스판에서 퀸이 서로 공격할 수 없게끔 배치할 수 있는 경우의 수 리턴
접근 방법
dfs에서 모두 돌리지 않고 특정 조건만 돌려주는 백트레킹 접근
퀸은 가로 세로 대각선 공격을 함으로 라인별로 하나씩 배치해주면 가로 체크할 필요가 없으니 라인별로 dfs 돌아주되, 세로, 대각선을 체크하면서 불필요한 부분들 continue로 최적화
대각선의 경우 한 라인씩 전진할 때마다 좌우 shift
코드
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func solution(_ n:Int) -> Int { | |
let banList: [Bool] = Array(repeating: false, count: n) | |
let leftCheck = Array(repeating: true, count: n) | |
let rifhtCheck = Array(repeating: true, count: n) | |
let line = Array(repeating: true, count: n) | |
var count = 0 | |
dfs(line, 0, leftCheck, rifhtCheck, banList, -3, n, &count) | |
return count | |
} | |
func dfs(_ line: [Bool], _ depth: Int, _ lc: [Bool], _ rc: [Bool], _ banList: [Bool], _ bf: Int, _ n: Int, _ count: inout Int) { | |
if depth == n { | |
count += 1 | |
return | |
} | |
for i in 0 ..< n { | |
if i == bf-1 || banList[i] || i == bf+1 { continue } // 이전에 넣은 값으로 비교 | |
else if lc[i] && rc[i] { // 대각선 | |
var line = line | |
line[i] = false | |
var lc = lc | |
var rc = rc | |
// 세로 제외요소 추가 | |
var banList = banList | |
banList[i] = true | |
// 오른쪽 왼쪽 둘다 좌우로 퍼져야 하니깐 둘다 값 넣어서 | |
lc[i] = false | |
rc[i] = false | |
// 왼쪽 shift | |
lc.removeFirst() | |
lc.append(true) | |
// 오른쪽 shift | |
rc.removeLast() | |
rc.insert(true, at: 0) | |
dfs(line, depth+1, lc, rc, banList, i, n, &count) | |
} | |
} | |
} | |
for i in 1 ..< 12 { | |
print(solution(i)) | |
} |
728x90
'개발 블로그 > 알고리즘' 카테고리의 다른 글
[Swift] 프로그래머스 - 수식 최대화 (0) | 2020.10.21 |
---|---|
[Swift] 프로그래머스 - N개의 최소공배수 (0) | 2020.10.12 |
[Swift] 백준 - N-Queen (0) | 2020.10.05 |
[Swift] 백준 - 종이의 개수 (0) | 2020.10.03 |
[Swift] 프로그래머스 - 행렬의 곱셈 (0) | 2020.09.29 |
250x250
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- Stack
- 프로그래머스 추석트래픽
- today extension
- 카카오 블라인드2018
- RxSwift
- 카카오블라인드2018
- presentStyle
- Github Search
- 1차 뉴스 클러스터링
- 괄호연산
- BaseTableViewController
- 아키택처
- UIModalPresentationStyle
- Swift
- TransitionStyle
- VIPER 패턴
- 백준 신입사원
- 위젯
- 프로그래머스 오픈채팅방
- 백준 1946
- 자기PR
- ReactorKit
- 카카오 블라인드 2018
- 프로그래머스 캐시
- Level 3
- ios
- 알고리즘
- Widget
- RxDataSource
- BaseViewController
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함