diff --git a/n-queens.py b/n-queens.py new file mode 100644 index 00000000..7a6c93df --- /dev/null +++ b/n-queens.py @@ -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=0 and c>=0: + if self.mat[r][c]: + return False + r -= 1 + c -= 1 + return True + + + + + + + + + + + \ No newline at end of file diff --git a/word-search.py b/word-search.py new file mode 100644 index 00000000..22988db2 --- /dev/null +++ b/word-search.py @@ -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