762. Sudoku Solver — Solvable?

MediumRecursionRecursion

Given a 9x9 Sudoku board as a 2D array where 0 represents an empty cell and 1..9 represent fixed digits, determine whether the board can be completed to a valid Sudoku solution. A valid solution places digits 1..9 in every cell such that each row, each column, and each of the nine 3x3 subgrids contains every digit from 1 to 9 exactly once. Return true if the given partial board is solvable (and return false if it already violates a Sudoku constraint). Use recursive backtracking.

Input: A JSON 9x9 2D integer array with entries in 0..9 (0 = empty).

Output: Return a boolean: true or false (lowercase).

Examples

Example 1
Input: [[5,3,4,6,7,8,9,1,2],[6,7,2,1,9,5,3,4,8],[1,9,8,3,4,2,5,6,7],[8,5,9,7,6,1,4,2,3],[4,2,6,8,5,3,7,9,1],[7,1,3,9,2,4,8,5,6],[9,6,1,5,3,7,2,8,4],[2,8,7,4,1,9,6,3,5],[3,4,5,2,8,6,1,7,9]]
Output: true
Explanation: Already a valid solved board.
Example 2
Input: [[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0]]
Output: true
Explanation: Empty board is solvable (many valid completions exist).
Example 3
Input: [[5,5,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0]]
Output: false
Explanation: Row 0 already has two 5's — invalid starting state.

Constraints

Asked by

AmazonMicrosoftGoogleAdobeFlipkart
Solve this problem in the editor →