leetcode -- 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.
判断数独是否合法:
1. 同一行中1-9出现次数不重复
2. 同一列中1-9出现次数不重复
3. 9宫格中1-9出现次数不重复
这里将1,2的判断在一个循环体中进行,分开进行跑大数据集时会TLE
1 public boolean isValidSudoku(char[][] board) { 2 // Start typing your Java solution below 3 // DO NOT write main() function 4 if(board.length == 0) 5 return false; 6 7 for(int i = 0; i < 9; i++){ 8 Set<Character> row = new HashSet<Character>(); 9 Set<Character> col = new HashSet<Character>(); 10 for(int j = 0; j < 9; j++){ 11 if(board[i][j] != '.'){ 12 if(row.contains(board[i][j])) 13 return false; 14 else { 15 row.add(board[i][j]); 16 } 17 } 18 19 if(board[j][i] != '.'){ 20 if(col.contains(board[j][i])) 21 return false; 22 else 23 col.add(board[j][i]); 24 } 25 26 } 27 } 28 29 for(int i = 0; i < 9; i+=3){ 30 for(int j = 0; j < 9; j+=3){ 31 Set<Character> container = new HashSet<Character>(); 32 for(int m = 0; m < 3; m++){ 33 for(int n = 0; n < 3; n++){ 34 if(board[m + i][n + j] == '.'){ 35 continue; 36 } 37 if(container.contains(board[m + i][n + j])) 38 return false; 39 else { 40 container.add(board[m + i][n + j]); 41 } 42 } 43 44 } 45 container.clear(); 46 } 47 } 48 return true; 49 50 }