CodexBloom - Programming Q&A Platform

scenarios with Recursive Backtracking for N-Queens in Python - Stack Overflow scenarios

👀 Views: 100 💬 Answers: 1 📅 Created: 2025-06-13
algorithms backtracking n-queens Python

Quick question that's been bugging me - I'm having a hard time understanding I'm trying to implement the N-Queens question using a recursive backtracking algorithm in Python, but I'm running into a stack overflow behavior when dealing with larger board sizes (specifically, 15x15 and above)... I’ve set up the board as a 2D list and am using a helper function to check for valid placements. Strangely, it works perfectly for smaller sizes, like 8x8 and 10x10, but the recursion depth exceeds the limit for larger sizes. Here's the code I have: ```python class NQueens: def __init__(self, n): self.n = n self.solutions = [] self.board = [[0] * n for _ in range(n)] def solve(self): self.backtrack(0) def backtrack(self, row): if row == self.n: self.solutions.append(self.construct_solution()) return for col in range(self.n): if self.is_valid(row, col): self.board[row][col] = 1 self.backtrack(row + 1) self.board[row][col] = 0 def is_valid(self, row, col): for i in range(row): if self.board[i][col] == 1: return False if col - (row - i) >= 0 and self.board[i][col - (row - i)] == 1: return False if col + (row - i) < self.n and self.board[i][col + (row - i)] == 1: return False return True def construct_solution(self): return [''.join('Q' if c == 1 else '.' for c in row) for row in self.board] ``` When I run this with `NQueens(15).solve()`, I get a `RecursionError: maximum recursion depth exceeded in comparison`. I’ve tried increasing the recursion limit with `sys.setrecursionlimit()`, but that only delays the behavior without fixing the underlying scenario. Is there a better approach or optimization technique I could use to handle larger board sizes, or is there something fundamentally wrong with my implementation? Any insights would be greatly appreciated! My development environment is CentOS. Has anyone else encountered this? For reference, this is a production service. Am I approaching this the right way?