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 '.'.輸入一個二維數組表示的數獨版(board)。要求咱們判斷已經填入的數字是否知足數獨的規則。即知足每一行、每一列、每個粗線宮(3*3)內的數字均含1-9,不重複。沒有數字的格子用字符'.'表示。數組
例如:
spa
public boolean isValidSudoku(char[][] board) { for(int i = 0; i<9; i++){ HashSet<Character> rows = new HashSet<Character>(); HashSet<Character> columns = new HashSet<Character>(); HashSet<Character> cube = new HashSet<Character>(); for (int j = 0; j < 9;j++){ if(board[i][j]!='.' && !rows.add(board[i][j])) return false; if(board[j][i]!='.' && !columns.add(board[j][i])) return false; int RowIndex = 3*(i/3); int ColIndex = 3*(i%3); if(board[RowIndex + j/3][ColIndex + j%3]!='.' && !cube.add(board[RowIndex + j/3][ColIndex + j%3])) return false; } } return true; }
public boolean isValidSudoku(char[][] board) { boolean res = true; int length = 9; //判斷行 for(int i=0;i<length;i++){ HashSet<Character> temp = new HashSet<Character>(); for(char c : board[i]){ if(c != '.'){ if(!temp.add(c)){ return false; } } } } //判斷列 for(int i=0;i<length;i++){ HashSet<Character> temp = new HashSet<Character>(); for(int j=0;j<length;j++){ char c = board[j][i]; if(c != '.'){ if(!temp.add(c)){ return false; } } } } //判斷方塊 int[][] center = {{1,1},{1,4},{1,7},{4,1},{4,4},{4,7},{7,1},{7,4},{7,7}}; int[][] directs = {{-1,-1},{-1,0},{1,0},{0,-1},{0,0},{0,1},{1,-1},{1,0},{1,1}}; for(int[] a :center){ HashSet<Character> temp = new HashSet<Character>(); for(int[] direct : directs){ char c =board[direct[0]+a[0]][direct[1]+a[1]]; if(c != '.'){ if(!temp.add(c)){ return false; } } } } return res; }