Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:

  1. Each row must contain the digits 1-9 without repetition.
  2. Each column must contain the digits 1-9 without repetition.
  3. Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition.

[leetcode]36. Valid Sudoku验证数独-LMLPHP

The Sudoku board could be partially filled, where empty cells are filled with the character '.'.

题意:

验证数独

Solution1: HashMap

用int[] map = new int[256] 作为一件简化版的hashmap

扫row、col、box

当前数字c若没在map里出现,则map[c] ++; 若在map里出现过,说明有重复,则返回false。

[leetcode]36. Valid Sudoku验证数独-LMLPHP

[leetcode]36. Valid Sudoku验证数独-LMLPHP

[leetcode]36. Valid Sudoku验证数独-LMLPHP

code

 public class ValidSudoku {
public boolean isValidSudoku(char[][] board) {
// corner case
if (board == null || board.length != 9 || board[0].length != 9)
return false;
//row
for (int row = 0; row < 9; row++) {
char[] map = new char[256];
for (int i = 0; i < 9; i++) {
char c = board[row][i];
if (c != '.') {
if (map[c] > 0) {
return false;
} else {
map[c]++;
}
}
}
}
// col
for (int col = 0; col < 9; col++) {
char[] map = new char[256];
for (int i = 0; i < 9; i++) {
char c = board[i][col];
if (c != '.') {
if (map[c] > 0) {
return false;
} else {
map[c]++;
} }
}
}
//box
for (int box = 0; box < 9; box++) {
char[] map = new char[256];
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
char c = board[row + 3 * (box / 3)][col + 3 * (box % 3)];
if (c != '.') {
if (map[c] > 0) {
return false;
} else {
map[c]++;
} } } } }
return true;
}
}
05-11 09:39