37. Sudoku Solver

Description

Write a program to solve a Sudoku puzzle by filling the empty cells.

A sudoku solution must satisfy all of the following rules:

  1. Each of the digits 1-9 must occur exactly once in each row.

  2. Each of the digits 1-9 must occur exactly once in each column.

  3. Each of the the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.

Empty cells are indicated by the character '.'.

Constraints

  • The given board contain only digits 1-9 and the character '.'.

  • You may assume that the given Sudoku puzzle will have a single unique solution.

  • The given board size is always 9x9.

Approach

Examples

Input:

A sudoku puzzle...

Output:

...and its solution numbers marked in red.

Solutions

/**
 * Time complexity : 
 * Space complexity : 
 */

class Solution {
    private static final int SIZE = 9;
    public void solveSudoku(char[][] board) {
        Set<String> tracker = new HashSet<>();
        
        for(int i = 0; i < SIZE; i++) {
            for(int j = 0; j < SIZE; j++) {
                char ch = board[i][j];
                if(board[i][j] != '.') {
                    tracker.add(ch + "r" + i);
                    tracker.add(ch + "c" + j);
                    tracker.add(ch + "b" + i/3 + "-" + j/3);
                }
            }
        }
        
        solve(board, tracker);
    }
    private boolean solve(char[][] board, Set<String> tracker) {
        for(int row = 0; row < SIZE; row++) {
            for(int col = 0; col < SIZE; col++) {
                if(board[row][col] == '.') {
                    for(char n = '1'; n <= '9'; n++) {
                        
                        // check whether number already present
                        if(tracker.contains(n + "r" + row)
                           || tracker.contains(n + "c" + col)
                           || tracker.contains(n + "b" + row/3 + "-" + col/3)) {
                            continue;
                        }
                        
                        board[row][col] = n;
                        
                        tracker.add(n + "r" + row);
                        tracker.add(n + "c" + col);
                        tracker.add(n + "b" + row/3 + "-" + col/3);
                        
                        if(solve(board, tracker)) return true;
                        
                        tracker.remove(n + "r" + row);
                        tracker.remove(n + "c" + col);
                        tracker.remove(n + "b" + row/3 + "-" + col/3);
                        
                        board[row][col] = '.';
                        
                    }
                    return false;
                }
            }
        }
        return true;
    }
}

Follow up

  • Solving Sudoku using Bit-wise Algorithm - GFG

Last updated

Was this helpful?