Given a partially filled 9×9 2D array ‘grid’, the goal is to assign digits (from 1 to 9) to the empty cells so that every row, column, and subgrid of size 3×3 contains exactly one instance of the digits from 1 to 9.
The Naive Algorithm is to generate all possible configurations of numbers from 1 to 9 to fill the empty cells. Try every configuration one by one until the correct configuration is found.
Like all other Backtracking problems, we can solve Sudoku by one by one assigning numbers to empty cells. Before assigning a number, we check whether it is safe to assign. We basically check that the same number is not present in the current row, current column and current 3X3 subgrid. After checking for safety, we assign the number, and recursively check whether this assignment leads to a solution or not. If the assignment doesn’t lead to a solution, then we try the next number for the current empty cell. And if none of the number (1 to 9) leads to a solution, we return false.
Find row, col of an unassigned cell If there is none, return true For digits from 1 to 9 a) If there is no conflict for digit at row, col assign digit to row, col and recursively try fill in rest of grid b) If recursion successful, return true c) Else, remove digit and try another If all digits have been tried and nothing worked, return false
Following are the implementation for Sudoku problem. It prints the completely filled grid as output.
3 1 6 5 7 8 4 9 2 5 2 9 1 3 4 7 6 8 4 8 7 6 2 9 5 3 1 2 6 3 4 1 5 9 8 7 9 7 4 8 6 3 1 2 5 8 5 1 7 9 2 6 4 3 1 3 8 9 4 7 2 5 6 6 9 2 3 5 1 8 7 4 7 4 5 2 8 6 3 1 9
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Program for Sudoku Generator
- Check if given Sudoku board configuration is valid or not
- Count of cells in a matrix which give a Fibonacci number when the count of adjacent cells is added
- Queries to find the last non-repeating character in the sub-string of a given string
- Find a sub matrix with maximum XOR
- Microsoft Interview Experience for Software Developer
- Print an N x M matrix such that each row and column has all the vowels in it
- Check if the given matrix is increasing row and column wise
- Interview with Microsoft (office 365 Hyderabad team) at their Bengaluru office.
- Amazon Interview -SDE 1 Interview Experience
- Queries for bitwise OR in the given matrix
- Queries for bitwise AND in the given matrix
- Minimum steps required to reach the end of a matrix | Set 2
- Microsoft Interview SDE intern 2019