public class Solution {
public boolean isValidSudoku(char[][] board) {
int row = board.length;
int col = board[0].length;
HashSet<Character> hs = new HashSet<Character>();
// check if rows are valid
for (int i=0; i<row; i++) {
for (int j=0; j<col; j++)
if (board[i][j] != '.') {
if (hs.contains(board[i][j])) return false;
hs.add(board[i][j]);
}
hs.clear();
}
hs.clear();
// check if columns are valid
for (int j=0; j<col; j++) {
for (int i=0; i<row; i++)
if (board[i][j] != '.') {
if (hs.contains(board[i][j])) return false;
hs.add(board[i][j]);
}
hs.clear();
}
hs.clear();
// check if boxes are valid
for (int k=0; k<9; k++) {
int box_row = k / 3 * 3, box_col = k % 3 * 3; // locate the start indices of a box
for (int l=0; l<9; l++) // iterate every location in a box
if (board[box_row+l/3][box_col+l%3] != '.') {
if (hs.contains(board[box_row+l/3][box_col+l%3])) return false;
hs.add(board[box_row+l/3][box_col+l%3]);
}
hs.clear();
}
return true;
}
}
Leetcode 36. Valid Sudoku
最新推荐文章于 2022-07-31 21:20:38 发布