Write a 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 93x3
sub-boxes of the grid.
The '.'
character indicates empty cells.
Example 1:
Input: board = [["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: [["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"]] Explanation: The input board is shown above and the only valid solution is shown below:
Constraints:
board.length == 9
board[i].length == 9
board[i][j]
is a digit or'.'
.- It is guaranteed that the input board has only one solution.
Companies:
DoorDash, Microsoft, Amazon, Google, Intuit, Bloomberg, Adobe, Uber
Related Topics:
Array, Backtracking, Matrix
Similar Questions:
// OJ: https://leetcode.com/problems/sudoku-solver/
// Author: github.com/lzl124631x
// Time: O((9!)^9)
// Space: O(81)
class Solution {
int row[9][9] = {}, col[9][9] = {}, box[9][9] = {};
bool valid(int x, int y, int i) {
return row[x][i] == 0 && col[y][i] == 0 && box[x / 3 * 3 + y / 3][i] == 0;
}
bool dfs(vector<vector<char>> &A, int x, int y) {
if (y == 9) {
++x;
y = 0;
}
if (x == 9) return true;
if (A[x][y] == '.') {
for (int i = 0; i < 9; ++i) {
if (!valid(x, y, i)) continue;
A[x][y] = '1' + i;
row[x][i] = col[y][i] = box[x / 3 * 3 + y / 3][i] = 1;
if (dfs(A, x, y + 1)) return true;
row[x][i] = col[y][i] = box[x / 3 * 3 + y / 3][i] = 0;
A[x][y] = '.';
}
return false;
}
return dfs(A, x, y + 1);
}
public:
void solveSudoku(vector<vector<char>>& A) {
for (int i = 0; i < 9; ++i) {
for (int j = 0; j < 9; ++j) {
if (A[i][j] == '.') continue;
row[i][A[i][j] - '1'] = 1;
col[j][A[i][j] - '1'] = 1;
box[i / 3 * 3 + j / 3][A[i][j] - '1'] = 1;
}
}
dfs(A, 0, 0);
}
};