Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 72a1fb4

Browse files
[풀이 추가] 리드미 테스트용 22.03.31 1문제, N-Queen.js
1 parent 8aca2be commit 72a1fb4

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

‎level-3/N-Queen.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
//https://github.com/codeisneverodd/programmers-coding-test
2+
//완벽한 정답이 아닙니다.
3+
//정답 1 - codeisneverodd
4+
function solution(n) {
5+
/*
6+
1. 0번째 행에 0번째 queen을 놓는다.
7+
2. 그 다음 행의 퀸은 이전 퀸들의 범위와 겹치지 않는 곳에 놓는다. 퀸은 한 행에 반드시 하나 두어야한다.
8+
3. 마지막 열까지 도달하면 성공으로 간주하고 answer에 1을 더한다.
9+
4. 0번째 queen의 위치를 바꿔가며 모두 시도한다.
10+
4. 단, 체스판은 일차원 배열로 선언하고 index = 행, 값 = 열 로 생각한다.
11+
*/
12+
let answer = 0;
13+
const canBePlacedOn = (chess, currentRow) => {
14+
//해당 행에 둔 queen이 유효한지
15+
for (let prevRow = 0; prevRow < currentRow; prevRow++) {
16+
const onDiagonal = currentRow - prevRow === Math.abs(chess[currentRow] - chess[prevRow])
17+
const onStraight = chess[prevRow] === chess[currentRow]
18+
if (onDiagonal || onStraight) return false
19+
}
20+
return true
21+
}
22+
const placeQueen = (chess, currentRow) => {
23+
//queen을 배치하다가 끝 행에 도착하면 1을 리턴, 도착하지 못하면 0을 리턴하여, 재귀적으로 모든 경우를 합하여 리턴
24+
let count = 0
25+
if (currentRow === chess.length) return 1
26+
for (let currentQueen = 0; currentQueen < n; currentQueen++) {
27+
//queen을 우선 배치한 후 가능한지 살펴본다.
28+
chess[currentRow] = currentQueen
29+
if (canBePlacedOn(chess, currentRow)) count += placeQueen(chess, currentRow + 1)
30+
}
31+
return count
32+
}
33+
for (let firstQueen = 0; firstQueen < n; firstQueen++) {
34+
const chess = new Array(n).fill(-1)
35+
chess[0] = firstQueen
36+
answer += placeQueen(chess, 1)
37+
}
38+
return answer;
39+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /