题目描述:
判断一个 9x9 的数独是否有效。只需要根据以下规则,验证已经填入的数字是否有效即可。
- 数字
1-9
在每一行只能出现一次。 - 数字
1-9
在每一列只能出现一次。 - 数字
1-9
在每一个以粗实线分隔的3x3
宫内只能出现一次。
如图是一个部分填充的有效的数独
数独部分空格内已填入了数字,空白格用 '.'
表示。
示例 1: 输入: [ ["5","3",".",".","7",".",".",".","."], ["6",".",".","1","9","5",".",".","."], [".","9","8",".",".",".",".","6","."], ["8",".",".",".","6",".",".",".","3"], ["4",".",".","8",".","3",".",".","1"], ["7",".",".",".","2",".",".",".","6"], [".","6",".",".",".",".","2","8","."], [".",".",".","4","1","9",".",".","5"], [".",".",".",".","8",".",".","7","9"] ] 输出: true 示例 2: 输入: [ ["8","3",".",".","7",".",".",".","."], ["6",".",".","1","9","5",".",".","."], [".","9","8",".",".",".",".","6","."], ["8",".",".",".","6",".",".",".","3"], ["4",".",".","8",".","3",".",".","1"], ["7",".",".",".","2",".",".",".","6"], [".","6",".",".",".",".","2","8","."], [".",".",".","4","1","9",".",".","5"], [".",".",".",".","8",".",".","7","9"] ] 输出: false
说明:
- 一个有效的数独(部分已被填充)不一定是可解的。
- 只需要根据以上规则,验证已经填入的数字是否有效即可。
- 给定数独序列只包含数字
1-9
和字符'.'
。 - 给定数独永远是
9x9
形式的。
分析:1.可通过遍历每一列、每一行、每个3*3格子判断是否有重复元素
此解法执行时间11ms ,超过82%Java提交记录(2019.4.27)
1 class Solution { 2 public static boolean isValidSudoku(char[][] board) { 3 4 HashSet<Character> set=new HashSet<Character>();
//判断每一行 5 for(int i=0;i<9;i++){ 6 for(int j=0;j<9;j++) { 7 if(board[i][j]!='.') { 8 if(!set.add(board[i][j])) 9 return false; 10 } 11 } 12 set.clear(); 13 }
//判断每一列 14 for(int i=0;i<9;i++){ 15 for(int j=0;j<9;j++) { 16 if(board[j][i]!='.') { 17 if(!set.add(board[j][i])) 18 return false; 19 } 20 } 21 set.clear(); 22 }
//判断每个3*3格子 23 for(int i=0;i<9;i+=3) { 24 for(int j=0;j<9;j+=3){ 25 for(int k=0;k<3;k++) 26 for(int l=0;l<3;l++) { 27 if(board[i+k][j+l]!='.') 28 if(!set.add(board[i+k][j+l])) 29 return false; 30 } 31 set.clear(); 32 } 33 34 } 35 return true; 36 } 37 }
2.提交记录中最快的:执行1ms
1 class Solution { 2 boolean canPut(char[][] board, int i, int j, char v) { 3 for(int k = 0; k < 9; k++) { 4 if(board[i][k] == v 5 || board[k][j] == v 6 || board[i / 3 * 3 + k % 3][j / 3 * 3 + k / 3] == v) { 7 return false; 8 } 9 } 10 return true; 11 } 12 public boolean isValidSudoku(char[][] board) { 13 for(int i = 0; i < 9; i++) { 14 for(int j = 0; j <9; j++) { 15 if(board[i][j] != '.') { 16 char t = board[i][j]; 17 board[i][j] = '.'; 18 if(!canPut(board, i, j, t)) 19 return false; 20 board[i][j] = t; 21 } 22 } 23 } 24 return true; 25 } 26 }