Question
Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
The Sudoku board could be partially filled, where empty cells are filled with the character '.'
.
A partially filled sudoku which is valid.
Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
Stats
Frequency | 2 |
Difficulty | 2 |
Adjusted Difficulty | 2 |
Time to use | ---------- |
Ratings/Color = 1(white) 2(lime) 3(yellow) 4/5(red)
Solution
This is not a difficult problem.
Make use of three for-loops and nine arrays of length 9 (for each loop) to mark the status, then do DFS search.
However, I also found a very concise solution. Read below.
My code
public class Solution {
public boolean isValidSudoku(char[][] board) {
if (board == null || board.length == 0) {
return false;
}
int N = board.length;
for (int i = 0; i < N; i++) {
boolean[] foo = new boolean[N];
// validate each row
for (int j = 0; j < N; j++) {
if (board[i][j] != '.') {
if (foo[board[i][j] - '1']) {
return false;
}
foo[board[i][j] - '1'] = true;
}
}
foo = new boolean[N];
// validate each column
for (int j = 0; j < N; j++) {
if (board[j][i] != '.') {
if (foo[board[j][i] - '1']) {
return false;
}
foo[board[j][i] - '1'] = true;
}
}
}
for (int a = 0; a < 3; a++) {
for (int b = 0; b < 3; b++) {
boolean[] foo = new boolean[N];
for (int c = 0; c < 3; c++) {
for (int d = 0; d < 3; d++) {
if (board[a * 3 + c][b * 3 + d] != '.') {
if (foo[board[a * 3 + c][b * 3 + d] - '1']) {
return false;
}
foo[board[a * 3 + c][b * 3 + d] - '1'] = true;
}
}
}
}
}
return true;
}
}
The following solution is from this blog. It’s a very clever and surprisingly concise code.
public boolean isValidSudoku(char[][] board) {
boolean[][] rows = new boolean[9][9];
boolean[][] cols = new boolean[9][9];
boolean[][] blocks = new boolean[9][9];
for (int i = 0; i < 9; ++i) {
for (int j = 0; j < 9; ++j) {
int c = board[i][j] - '1';
if (board[i][j] == '.') continue;
if (rows[i][c] || cols[j][c] || blocks[i - i % 3 + j / 3][c])
return false;
rows[i][c] = cols[j][c] = blocks[i - i % 3 + j / 3][c] = true;
}
}
return true;
}