Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 74 additions & 0 deletions n-queens.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
''' Time Complexity : O(n * n!) ;
Space Complexity : O(n^2 + n)
Did this code successfully run on Leetcode : Yes
Any problem you faced while coding this : No


Approach - Place the queen if safe , go to next row. if cannot place in next row, backtrack by making 1->0
'''

class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
self.mat=[[False for _ in range(n)] for _ in range(n)]
self.result = []

def helper(i, j, n):
#base
if i == n:
li = []
for r in range(n):
s = ""
for c in range(n):
if self.mat[r][c]:
s += "Q"
else:
s += "."
li.append(s)
self.result.append(li)
return

for j in range(n):
if self.isSafe(i,j,n):
self.mat[i][j] = True
helper(i+1,j,n)
self.mat[i][j] = False

helper(0,0,n)
return self.result


def isSafe(self,i, j,n):
r,c = i, j
#up check
while r>=0:
if self.mat[r][c]:
return False
r -= 1

r,c = i, j
#right check diagonal
while r>=0 and c<n:
if self.mat[r][c]:
return False
r -= 1
c += 1

r,c = i, j
#right left diagonal
while r>=0 and c>=0:
if self.mat[r][c]:
return False
r -= 1
c -= 1
return True











41 changes: 41 additions & 0 deletions word-search.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
''' Time Complexity : O(m * n * 4^L) ; L - len of word
Space Complexity : O(L)
Did this code successfully run on Leetcode : Yes
Any problem you faced while coding this : No

Approach : First do left pass to calculate running product.
Then second iteration from right to left and updating the new product
'''

class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
rows, cols = len(board),len(board[0])
dirs = [(-1,0),(0,1),(1,0),(0,-1)]

if rows==1 and cols == 1 and board[0][0] == word:
return True

def dfs(board, word, i, j, s):
#base
if s == len(word):
return True
if board[i][j] != word[s]:
return False
#logic
#action
char = board[i][j]
board[i][j] = "#"
for dir in dirs:
r = dir[0] + i
c = dir[1] + j
if 0<=r<rows and 0<=c<cols:
if dfs(board, word, r, c, s+1):
return True
#backtrack
board[i][j] = char

for i in range(rows):
for j in range(cols):
if dfs(board, word, i, j, 0):
return True
return False