ํฐ์คํ ๋ฆฌ ๋ทฐ
๐ง๐ป๐ป ์ฝ๋ฉํ
์คํธ/LeetCode
[LeetCode] 51. N-Queens (Python / JavaScript)
10000COW 2023. 1. 9. 16:09728x90
LeetCode 51. N-Queens (Python / JavaScript)
https://leetcode.com/problems/n-queens/description/
Python
def solveQueens(n):
col = set()
posDiag = set() # (r + c)
negDiag = set() # (r - c)
res = []
board = [["ใ
"] * n for i in range(n)]
def backtrack(r):
if r == n:
copy = ["".join(row) for row in board]
res.append(copy)
print('res', res)
for c in range(n):
if c in col or (r+c) in posDiag or (r-c) in negDiag:
continue
col.add(c)
posDiag.add(r+c)
negDiag.add(r-c)
board[r][c] = "Q"
backtrack(r+1)
col.remove(c)
posDiag.remove(r + c)
negDiag.remove(r - c)
board[r][c] = "ใ
"
backtrack(0)
return len(res)
JavaScript
function solveQueens(n){
const cols = new Set();
const posDig = new Set();
const negDig = new Set();
const res = []
const board = [];
for(let i=0; i < n; i++){
board[i] = []
for(let j=0; j < n; j++){
board[i][j] = '.';
}
}
function backTrack(r){
if(r === n){
for(let i=0; i<n; i++){
res.push(board[i].join(''))
}
console.log(res);
}
for(let c=0; c < n; c++){
if(cols.has(c) || posDig.has(r+c) || negDig.has(r-c)){
continue;
}
else{
cols.add(c);
posDig.add(r+c);
negDig.add(r-c);
board[r][c] = "Q";
backTrack(r+1);
cols.delete(c);
posDig.delete(r+c);
negDig.delete(r-c);
board[r][c] = "."
}
}
}
backTrack(0)
return res
}
728x90
'๐ง๐ปโ๐ป ์ฝ๋ฉํ ์คํธ > LeetCode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[LeetCode][DFS] 200. Number of Islands (0) | 2022.10.23 |
---|
๊ณต์ง์ฌํญ
์ต๊ทผ์ ์ฌ๋ผ์จ ๊ธ
์ต๊ทผ์ ๋ฌ๋ฆฐ ๋๊ธ
- Total
- Today
- Yesterday
๋งํฌ
TAG
- ๋ฐ์ดํฐ๋ฒ ์ด์ค
- ๋ฆฌ์กํธ
- ๋ธ๋ผ์ฐ์
- Context API
- ์๊ณ ๋ฆฌ์ฆ
- error
- leetcode
- react
- Component
- BOJ
- state
- Python
- CSS
- JavaScript
- ์๋ฌ
- ์ ๋ ฌ
- React Query
- git
- DOM
- Browser
- mdn
- ํ์ด์ฌ
- ์๋ฃ๊ตฌ์กฐ
- github
- zustand
- useState
- ๊ทธ๋ํ
- DB
- ์๋ฐ์คํฌ๋ฆฝํธ
- ํจ์
์ผ | ์ | ํ | ์ | ๋ชฉ | ๊ธ | ํ |
---|---|---|---|---|---|---|
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 |
๊ธ ๋ณด๊ดํจ
250x250