From 8b92ec427112bb22cc7299f06e226c594fdf9109 Mon Sep 17 00:00:00 2001 From: Sahithipsl470 Date: Mon, 9 Mar 2026 20:20:00 -0400 Subject: [PATCH] "Backtracking-3 done" --- Problem-1.java | 81 ++++++++++++++++++++++++++++++++++++++++++++++++++ Problem-1.py | 60 +++++++++++++++++++++++++++++++++++++ Problem-2.py | 35 ++++++++++++++++++++++ 3 files changed, 176 insertions(+) create mode 100644 Problem-1.java create mode 100644 Problem-1.py create mode 100644 Problem-2.py diff --git a/Problem-1.java b/Problem-1.java new file mode 100644 index 00000000..a6f082c1 --- /dev/null +++ b/Problem-1.java @@ -0,0 +1,81 @@ +// Time Complexity : O(N!) // Each row tries N columns, pruning reduces possibilities +// Space Complexity : O(N) // recursion stack + one array for column placements +// Did this code successfully run on Leetcode : Yes +// Any problem you faced while coding this : No + +// Explanation: +// The code places queens row by row, checking for conflicts with previously placed queens. +// It uses DFS/backtracking to explore all valid configurations. +// Each valid placement is added to the solution list. + +class Solution { + List> result; + + public List> solveNQueens(int n) { + boolean[][] board = new boolean[n][n]; + result = new ArrayList<>(); + helper(n, 0, board); + return result; + } + + private void helper(int n, int r, boolean[][] board) { + if (r == n) { + result.add(changeBoard(board, n)); + return; + } + + for (int c = 0; c < n; c++) { + if (canPut(r, c, n, board)) { + board[r][c] = true; + helper(n, r + 1, board); + board[r][c] = false; // backtrack + } + } + } + + private boolean canPut(int i, int j, int n, boolean[][] board) { + // vertical check + for (int r = 0; r < i; r++) { + if (board[r][j]) { + return false; + } + } + + // diagonal left-up + int r = i - 1, c = j - 1; + while (r >= 0 && c >= 0) { + if (board[r][c]) { + return false; + } + r--; + c--; + } + + // diagonal right-up + r = i - 1; + c = j + 1; + while (r >= 0 && c < n) { + if (board[r][c]) { + return false; + } + r--; + c++; + } + + return true; + } + + private List changeBoard(boolean[][] board, int n) { + List formatted = new ArrayList<>(); + + for (int i = 0; i < n; i++) { + StringBuilder sb = new StringBuilder(); + for (int j = 0; j < n; j++) { + sb.append(board[i][j] ? 'Q' : '.'); + } + formatted.add(sb.toString()); + } + + return formatted; + } +} diff --git a/Problem-1.py b/Problem-1.py new file mode 100644 index 00000000..44118bcf --- /dev/null +++ b/Problem-1.py @@ -0,0 +1,60 @@ +# Time Complexity : O(N!) # Each row tries N columns, pruning reduces possibilities +# Space Complexity : O(N) # recursion stack + one array for column placements +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : No + +# Explanation: +# The code places queens row by row, checking for conflicts with previously placed queens. +# It uses DFS/backtracking to explore all valid configurations. +# Each valid placement is added to the solution list. +class Solution: + def solveNQueens(self, n: int) -> List[List[str]]: + board = [[False for _ in range(n)] for _ in range(n)] + self.result = [] + self.helper(n, 0,board) + return self.result + def helper(self, n,r,board): + if r == n: + copy_board = [row[:] for row in board] + self.changeBoard(copy_board,n) + self.result.append(copy_board) + return + for c in range(n): + if self.canPut(r,c,n,board): + board[r][c] = True + self.helper(n, r+1,board) + board[r][c]=False + + def canPut(self, i,j,n,board): + #vertical + for r in range(i): + if board[r][j] == True: + return False + + #diagonal-left-up + r, c = i - 1, j - 1 + while r >= 0 and c >= 0: + if board[r][c]: + return False + r -= 1 + c -= 1 + + # diagonal right-up + r, c = i - 1, j + 1 + while r >= 0 and c < n: + if board[r][c]: + return False + r -= 1 + c += 1 + return True + + def changeBoard(self, board, n): + for i in range(n): + board[i] = ''.join('Q' if cell else '.' for cell in board[i]) + + + + + + + diff --git a/Problem-2.py b/Problem-2.py new file mode 100644 index 00000000..1e3b9845 --- /dev/null +++ b/Problem-2.py @@ -0,0 +1,35 @@ +# Time Complexity : O(M * N * 4^L) # MxN = board size, L = length of word +# Space Complexity : O(L) # recursion stack for DFS +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : No + +# Explanation: +# The code searches for a word in a 2D grid by starting DFS from every cell. +# Each DFS explores neighboring cells recursively while marking visited cells temporarily. +# If the word is fully matched, it returns True; otherwise it backtracks and continues. + +class Solution: + def exist(self, board: List[List[str]], word: str) -> bool: + n = len(board) + m = len(board[0]) + + def dfs(r, c, idx): + if idx == len(word): + return True + if r < 0 or r >= n or c < 0 or c >= m or board[r][c] != word[idx]: + return False + + temp = board[r][c] + board[r][c] = "#" # mark visited + found = (dfs(r+1, c, idx+1) or + dfs(r-1, c, idx+1) or + dfs(r, c+1, idx+1) or + dfs(r, c-1, idx+1)) + board[r][c] = temp # unmark + return found + + for r in range(n): + for c in range(m): + if board[r][c] == word[0] and dfs(r, c, 0): + return True + return False \ No newline at end of file