Monday, January 2, 2023

Sudoku Solver

I had seen a hard problem on Leetcode regarding Sudoku Solver a few days back and had been thinking of a solution since then. I have solved Sudoku previously and thought of converting the manual approach to a programmatic way of solving it. Here is the final solution which got accepted by Leetcode.

The idea is to keep finding a grid to put a number in, try putting numbers between 1 through 9 into it and check for validity of the board with each number. If the board is valid after putting in a number, try another grid. If the board fails the validity check for all the numbers from 1 through 9, put back the initial dot ('.') onto that grid and return to previous state of the grid i.e. Backtrack. At this previous state, try another number on the previous grid. Keep doing this until you get a solution. The Leetcode problem above asks to assume that there exists a solution.