diff --git a/Problem1.py b/Problem1.py new file mode 100644 index 00000000..f7198c10 --- /dev/null +++ b/Problem1.py @@ -0,0 +1,56 @@ +#N-Queens + +# Time complexity -> N! since for each new row it is 1 less space to place atleast +# Space Complexity -> O(N) coming from the set and queens column position per row +# Logic -> for each row place the queen a each column, then recurse to next row and based on earlier placements validate +# and do the queen placement in current row and continue untill you found all the possible placements + + +class Solution: + def solveNQueens(self, n: int) -> List[List[str]]: + result = [] + queenDiagonalTracker = set() + queenAntDiagonalTracker = set() + queenColumnTracker = set() + + columnPositionPerRow = [0]*n + + def helper(row): + if row == n: + convertAndAddToResult() + return + for j in range(n): + if noCoflict(row, j): + columnPositionPerRow[row] = j + queenDiagonalTracker.add(row-j) + queenAntDiagonalTracker.add(row+j) + queenColumnTracker.add(j) + helper(row+1) + queenDiagonalTracker.remove(row-j) + queenAntDiagonalTracker.remove(row+j) + queenColumnTracker.remove(j) + columnPositionPerRow[row] = 0 + + def noCoflict(row, j): + # check top + if j in queenColumnTracker: return False + + #check diagonal + if (row-j) in queenDiagonalTracker: return False + + #check antiDiagonal + if (row+j) in queenAntDiagonalTracker: return False + + return True + + def convertAndAddToResult(): + tmp = [] + for i in range(n): + column = columnPositionPerRow[i] + tmp.append("."*(column) + "Q" + "."*(n-column-1)) + # tmp.append("".join(tmpResult[i])) + + result.append(tmp) + + helper(0) + return result \ No newline at end of file diff --git a/Problem2.py b/Problem2.py new file mode 100644 index 00000000..e2a8d7a3 --- /dev/null +++ b/Problem2.py @@ -0,0 +1,34 @@ +#Word Search + +# Time comlexity -> O(MxNx4^L) as for each index position in matrix we are checking the word by recrusion +# Space Complexity -> O(L) recusrive stack and set +# Logic -> iterate over each matrix, once you find 1st character, then see if word can be formed using DFS and using +# Backtrack for managing the visited items + +class Solution: + def exist(self, board: List[List[str]], word: str) -> bool: + dir = [(0,-1), (-1,0), (0,1), (1,0)] + visitedIndexes = set() + m = len(board) + n = len(board[0]) + wordLength = len(word) + + def helper(wordIndex, row, column): + if wordIndex == wordLength: + return True + charToCheck = word[wordIndex] + for r, c in dir: + if r+row>=0 and r+row= 0 and c+column < n and (r+row,c+column) not in visitedIndexes and charToCheck == board[r+row][c+column]: + visitedIndexes.add((r+row,c+column)) + if helper(wordIndex+1, r+row,c+column): + return True + visitedIndexes.remove((r+row,c+column)) + + for i in range(m): + for j in range(n): + if board[i][j] == word[0]: + visitedIndexes.add((i,j)) + if helper(1, i, j): + return True + visitedIndexes.remove((i,j)) + return False \ No newline at end of file