
Problem
Solution
Submissions
Sudoku Solver
Certification: Advanced Level
Accuracy: 100%
Submissions: 1
Points: 20
Write a Java program to solve a Sudoku puzzle by filling the empty cells. A sudoku solution must satisfy all of the following rules:
- Each of the digits 1-9 must occur exactly once in each row.
- Each of the digits 1-9 must occur exactly once in each column.
- Each of the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.
The '.' character indicates empty cells.
Example 1
- Input:
5 3 . | . 7 . | . . .
6 . . | 1 9 5 | . . .
. 9 8 | . . . | . 6 .
---------------------
8 . . | . 6 . | . . 3
4 . . | 8 . 3 | . . 1
7 . . | . 2 . | . . 6
---------------------
. 6 . | . . . | 2 8 .
. . . | 4 1 9 | . . 5
. . . | . 8 . | . 7 9 - Output: Filled sudoku board
- Explanation:
Step 1: Start with the given board with empty cells marked as '.'.
Step 2: Apply backtracking to fill in the empty cells one by one.
Step 3: For each empty cell, try digits 1-9 and validate against sudoku rules.
Step 4: If a valid digit is found, place it and move to the next empty cell.
Step 5: If no valid digit exists for a cell, backtrack and try different digits for previous cells.
Step 6: Continue until all empty cells are filled with valid digits.
Example 2
- Input:
. . 9 | 7 4 8 | . . .
7 . . | . . . | . . .
. 2 . | 1 . 9 | . . .
---------------------
. . 7 | . . . | 2 4 .
. 6 4 | . 1 . | 5 9 .
. 9 8 | . . . | 3 . .
---------------------
. . . | 8 . 3 | . 2 .
. . . | . . . | . . 6
. . . | 2 7 5 | 9 . . - Output: Filled sudoku board
- Explanation:
Step 1: Start with the given board with empty cells marked as '.'.
Step 2: Apply backtracking to fill in the empty cells one by one.
Step 3: For each empty cell, try digits 1-9 and validate against sudoku rules.
Step 4: If a valid digit is found, place it and move to the next empty cell.
Step 5: If no valid digit exists for a cell, backtrack and try different digits for previous cells.
Step 6: Continue until all empty cells are filled with valid digits.
Constraints
- The board size is fixed as a 9x9 grid
- The board will contain only digits 1-9 and the character '.' for empty cells
- The given board will have at least one solution
- Time Complexity: O(9^(n*n)) where n is the size of the board (in this case, 9)
- Space Complexity: O(n*n)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use backtracking algorithm to solve this problem.
- Start by finding an empty cell in the board.
- Try placing each digit 1-9 in the empty cell.
- For each digit, check if it's valid according to sudoku rules.
- If valid, place the digit and recursively solve for the next empty cell.
- If a solution is found, return true. If not, backtrack and try a different digit.
- If no digits work, reset the cell to empty and return false.