diff --git a/Problem1.py b/Problem1.py new file mode 100644 index 00000000..9b79901d --- /dev/null +++ b/Problem1.py @@ -0,0 +1,64 @@ +""" +TC: O(N!) {The complexity is bounded by the number of valid permutations of queen placements, which is close to N!, as we prune invalid branches aggressively.} +SC: O(N^2) {The space is dominated by the auxiliary N x N grid used to track attacked cells, plus O(N) for the recursion stack depth.} + +Approach: + +This problem is solved using a **backtracking** algorithm to find all unique solutions for placing N non-attacking queens. We attempt to place one queen per row, starting from the first row. For each row, we iterate through all columns. The key is an auxiliary N x N grid used to track which cells are already under attack (marked with a '1') by previously placed queens. When a queen is placed on a safe cell, we use the `updateGrid` helper to mark all cells in its column and both diagonals below it as attacked. We then make a recursive call for the next row. If we reach the end of the board with N queens placed, we record the solution. We **backtrack** by exploring the next column in the current row. + +The problem ran successfully on LeetCode. +""" +class Solution: + def solveNQueens(self, n: int) -> List[List[str]]: + + def inBounds(row, col): + return 0<=row= n: + if len(res) == n: + result.append(res[:][:]) + return + + #logic + for col in range(n): + if inBounds(row, col) and grid[row][col] == 0: + #place the queen + updated_grid = updateGrid(row, col, grid) + temp = ['.']*n + temp[col] = 'Q' + temp = "".join(temp) + res.append(temp) + backtrack(row+1, updated_grid, res) + res.pop() + + + result = [] + grid = [[0]*n for _ in range(n)] + backtrack(row=0, grid=grid, res = []) + return result \ No newline at end of file diff --git a/Problem2.py b/Problem2.py new file mode 100644 index 00000000..e69de29b