CodexBloom - Programming Q&A Platform

implementing Recursive Backtracking for Sudoku Solver in Java - StackOverflowError on Larger Puzzles

๐Ÿ‘€ Views: 3 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-06
java algorithm backtracking sudoku recursion Java

I'm collaborating on a project where I'm sure I'm missing something obvious here, but I've looked through the documentation and I'm still confused about I'm trying to implement a Sudoku solver using a recursive backtracking algorithm in Java, but I'm working with a `StackOverflowError` when I try to solve larger puzzles... My implementation seems to work fine for standard 9x9 Sudoku puzzles, but when I attempt to use it on a more complex puzzle, it crashes. Here's the code snippet for my backtracking function: ```java public boolean solveSudoku(int[][] board) { for (int row = 0; row < 9; row++) { for (int col = 0; col < 9; col++) { if (board[row][col] == 0) { // Empty cell for (int num = 1; num <= 9; num++) { if (isSafe(board, row, col, num)) { board[row][col] = num; // Try this number if (solveSudoku(board)) { return true; } board[row][col] = 0; // Backtrack } } return false; // If no number is valid } } } return true; // Solved } ``` The `isSafe` function checks if placing a number in a specific cell would violate Sudoku rules: ```java private boolean isSafe(int[][] board, int row, int col, int num) { for (int x = 0; x < 9; x++) { if (board[row][x] == num || board[x][col] == num || board[3 * (row / 3) + x / 3][3 * (col / 3) + x % 3] == num) { return false; } } return true; } ``` Iโ€™ve implemented memoization, but it doesnโ€™t seem to help with the larger puzzles. Iโ€™ve also tried increasing the stack size using the `-Xss` JVM option to no avail. What could be causing the stack overflow, and how can I optimize my algorithm to handle larger puzzles or complex configurations without crashing? My development environment is Ubuntu. I'd really appreciate any guidance on this. This is part of a larger application I'm building. I'm working with Java in a Docker container on Windows 11. I'm open to any suggestions. I'm using Java latest in this project.