原题链接在这里:https://leetcode.com/problems/valid-sudoku/
题目:
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.
题解:
先一行一行检查,再一列一列检查,这里注意外层for loop是j
最后一个一个小方块来检查,关键是如何检查sub box. 这里设值index 0-8 box, loop row with box/3*3 - box/3*3+3, loop column with box%3*3 - box%3*3+3.
Time Complexity: O(n^2). n = board.length. Space: O(1).
AC Java:
1 public class Solution { 2 public boolean isValidSudoku(char[][] board) { 3 if(board == null || board.length != 9 || board[0].length != 9){ 4 return false; 5 } 6 7 HashSet<Character> hs = new HashSet<Character>(); 8 //check each row 9 for(int i = 0; i<board.length; i++){ 10 hs.clear(); 11 for(int j = 0; j<board[0].length; j++){ 12 if(board[i][j] != '.'){ 13 if(!hs.contains(board[i][j])){ 14 hs.add(board[i][j]); 15 }else{ 16 return false; 17 } 18 } 19 } 20 } 21 22 //check each column 23 for(int j = 0; j<board[0].length; j++){ 24 hs.clear(); 25 for(int i = 0; i<board.length; i++){ 26 if(board[i][j] != '.'){ 27 if(!hs.contains(board[i][j])){ 28 hs.add(board[i][j]); 29 }else{ 30 return false; 31 } 32 } 33 } 34 } 35 36 //check each subbox 37 for(int box = 0; box<9; box++){ 38 hs.clear(); 39 for(int i = box/3*3; i<box/3*3+3; i++){ 40 for(int j = box%3*3; j<box%3*3+3; j++){ 41 if(board[i][j] != '.'){ 42 if(!hs.contains(board[i][j])){ 43 hs.add(board[i][j]); 44 }else{ 45 return false; 46 } 47 } 48 } 49 } 50 } 51 return true; 52 } 53 }