题目链接
有效的数独
题目描述
注意点
- board.length == 9
- board[i].length == 9
- board[i][j] 是一位数字(1-9)或者 ‘.’
解答思路
- 首先判断行是否满足数独条件,再判断列是否满足数独条件,最后再判断划分的3x3方格是否满足数独条件,中间有一处不满足则直接返回false,遍历完后都满足条件则返回true
代码
class Solution {public boolean isValidSudoku(char[][] board) {int row = board.length;int col = board[0].length;// 判断行for (int i = 0; i < row; i++) {int[] arr = new int[10];for (int j = 0; j < col; j++) {if (board[i][j] == '.') {continue;}if (arr[board[i][j] - '0'] != 0) {return false;}arr[board[i][j] - '0'] = 1;}}// 判断列for (int j = 0; j < col; j++) {int[] arr = new int[10];for (int i = 0; i < row; i++) {if (board[i][j] == '.') {continue;}if (arr[board[i][j] - '0'] != 0) {return false;}arr[board[i][j] - '0'] = 1;}}// 判断3 x 3方格for (int i = 0; i < row; i = i + 3) {for (int j = 0; j < col; j = j + 3) {if (!isValidSudokuSquare(board, i, j)) {return false;}}}return true;}public boolean isValidSudokuSquare(char[][] board, int x, int y) {int[] arr = new int[10];for (int i = 0; i < 3; i++) {for (int j = 0; j < 3; j++) {if (board[x + i][y + j] == '.') {continue;}if (arr[board[x + i][y + j] - '0'] != 0) {return false;}arr[board[x + i][y + j] - '0'] = 1; }}return true;}
}
关键点
- 有效数独的条件