Algo-Sim › Recursion & Backtracking

Sudoku Solver

Hard · Recursion & Backtracking · step through it in Java, Python and C++ on your own input

Fill each empty cell with every digit its row, column and box allow, and back up when a cell has none.

Problem

Fill the empty cells (.) of a 9 × 9 Sudoku board so that every row, every column and each of the nine 3 × 3 boxes contains the digits 1–9 exactly once. The board is modified in place, and the puzzle has exactly one solution.

Constraints

Edge cases to test

Follow-up questions

What makes it fast in practice?
Fill the cell with the fewest legal digits first (MRV) and keep 9-bit masks per row, column and box.
Is there a systematic method?
Exact cover with Knuth’s Algorithm X and dancing links.

Solution

Java

public void solveSudoku(char[][] board) {
    solve(board);
}

private boolean solve(char[][] board) {
    for (int r = 0; r < 9; r++) {
        for (int c = 0; c < 9; c++) {
            if (board[r][c] != '.') continue;
            for (char d = '1'; d <= '9'; d++) {
                if (!valid(board, r, c, d)) continue;
                board[r][c] = d;
                if (solve(board)) return true;
                board[r][c] = '.';
            }
            return false;
        }
    }
    return true;
}

private boolean valid(char[][] board, int r, int c, char d) {
    for (int i = 0; i < 9; i++) {
        if (board[r][i] == d || board[i][c] == d) return false;
        if (board[3 * (r / 3) + i / 3][3 * (c / 3) + i % 3] == d) return false;
    }
    return true;
}

Python

def solve_sudoku(board):
    def valid(r, c, d):
        for i in range(9):
            if board[r][i] == d or board[i][c] == d:
                return False
            if board[3 * (r // 3) + i // 3][3 * (c // 3) + i % 3] == d:
                return False
        return True

    def solve():
        for r in range(9):
            for c in range(9):
                if board[r][c] != ".":
                    continue
                for d in "123456789":
                    if not valid(r, c, d):
                        continue
                    board[r][c] = d
                    if solve():
                        return True
                    board[r][c] = "."
                return False
        return True

    solve()

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    void solveSudoku(vector<vector<char>> &board) {
        solve(board);
    }

    bool solve(vector<vector<char>> &board) {
        for (int r = 0; r < 9; r++) {
            for (int c = 0; c < 9; c++) {
                if (board[r][c] != '.')
                    continue;
                for (char d = '1'; d <= '9'; d++) {
                    if (!valid(board, r, c, d))
                        continue;
                    board[r][c] = d;
                    if (solve(board))
                        return true;
                    board[r][c] = '.';
                }
                return false;
            }
        }
        return true;
    }

    bool valid(vector<vector<char>> &board, int r, int c, char d) {
        for (int i = 0; i < 9; i++) {
            if (board[r][i] == d || board[i][c] == d)
                return false;
            if (board[3 * (r / 3) + i / 3][3 * (c / 3) + i % 3] == d)
                return false;
        }
        return true;
    }
};

More Recursion & Backtracking problems