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
- Maximum number of strings that can be formed with given zeros and ones
- Sort a 2D vector diagonally
- Longest common subarray in the given two arrays
- Maximum sum of elements divisible by K from the given array
- Google-Bangalore Interview Experience
- How I got selected for the TalentSprint Women Engineers (WE) Program powered by Google?
- Construct a matrix such that union of ith row and ith column contains every element from 1 to 2N-1
- Microsoft Interview Experience | Senior Software Engineer (4 Years Experienced)
- Microsoft Summer Internship Off Campus 2020
- Amazon Interview Experience for SDE-1 | Off-Campus ( Exp<1year)
- Sort the given Matrix | Memory Efficient Approach
- Encryption and Decryption of String according to given technique