1. 题目
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 ‘.’.
Note: A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
2. 思路
根据数独游戏的规则,一个9行9列的棋盘,每行每列和每一个3*3的小方格都不能有重复的数字,并且数字只能是0-9,逐一判断这些规则是否满足即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
public class { public boolean isValidSudoku (char [][] board) { if (board.length != 9 || board[0 ].length != 9 ){ return false ; } for (int i=0 ;i<9 ;i++){ int [] map = new int [10 ]; for (int j=0 ;j<9 ;j++){ if (board[i][j] == '.' )continue ; int num = board[i][j]-'0' ; if (map[num] == 1 ){ return false ; } map[num] = 1 ; } } for (int j=0 ;j<9 ;j++){ int [] map = new int [10 ]; for (int i=0 ;i<9 ;i++){ if (board[i][j] == '.' )continue ; int num = board[i][j]-'0' ; if (map[num] == 1 ){ return false ; } map[num] = 1 ; } } for (int i=0 ;i<9 ;i+=3 ){ for (int j=0 ;j<9 ;j+=3 ){ int [] map = new int [10 ]; for (int k=i;k<i+3 ;k++){ for (int l=j;l<j+3 ;l++){ if (board[k][l] == '.' )continue ; int num = board[k][l]-'0' ; if (map[num] == 1 ){ return false ; } map[num] = 1 ; } } } } return true ; } }
近期评论