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 cef087b

Browse files
N-Queens
1 parent f8619c8 commit cef087b

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

‎Backtracking/51-N-Queens.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
'''Leetcode- https://leetcode.com/problems/n-queens/ '''
2+
'''
3+
The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.
4+
5+
Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order.
6+
7+
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively.
8+
9+
Example 1:
10+
11+
Input: n = 4
12+
Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
13+
'''
14+
15+
16+
def solveNQueens(n):
17+
18+
cols = set()
19+
pos = set()
20+
neg = set()
21+
22+
res = []
23+
board = [["."] * n for i in range(n)]
24+
25+
def backtrack(r):
26+
if r == n:
27+
copy = ["".join(row) for row in board]
28+
res.append(copy)
29+
return
30+
31+
for c in range(n):
32+
if c in cols or (r + c) in pos or (r - c) in neg:
33+
continue
34+
35+
cols.add(c)
36+
pos.add(r+c)
37+
neg.add(r-c)
38+
board[r][c] = "Q"
39+
40+
backtrack(r+1)
41+
42+
cols.remove(c)
43+
pos.remove(r+c)
44+
neg.remove(r-c)
45+
board[r][c] = "."
46+
47+
backtrack(0)
48+
49+
return res
50+
51+
#T:O(n!)
52+
#S:O(N^2)

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,5 +20,6 @@ Check the notes for the explaination - [Notes](https://stingy-shallot-4ea.notion
2020
- [x] [Palindrome Partitioning](Backtracking/131-Palindrome-Partitioning.py)
2121
- [x] [Letter Combinations of a Phone Number](Backtracking/17-Letter-Combinations-of-a-Phone-Number.py)
2222
- [x] [Generalized Abbreviation](Backtracking/320-Generalized-Abbreviation.py)
23+
- [x] [N-Queens](Backtracking/51-N-Queens.py)
2324

2425

0 commit comments

Comments
(0)

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