标签:
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.
Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
首先检查是否是9*9 矩阵;
其次依次检查每行,每列和内部各个3*3 矩阵是否满足要求。
建立int[] temp, temp.length = 9 来存储1-9 的个数,当temp[i] > 1时,说明有重复数字出现,返回false.
Java code:
public class Solution { public boolean isValidSudoku(char[][] board) { if(board == null || board.length !=9 || board[0].length != 9){ return false; } //check each row for(int i = 0; i < 9; i++){ int[] temp = new int[9]; for(int j = 0; j < 9; j++){ if(board[i][j] != ‘.‘){ temp[board[i][j] - ‘1‘]++; if(temp[board[i][j] - ‘1‘] > 1){ return false; } } } } //check each column for(int j = 0; j < 9; j++){ int[] temp = new int[9]; for(int i = 0; i < 9; i++){ if(board[i][j] != ‘.‘){ temp[board[i][j] - ‘1‘]++; if(temp[board[i][j] - ‘1‘] > 1){ return false; } } } } //check each 3*3 matrix for(int i = 0; i < 3; i++) { for(int j = 0; j < 3; j++){ int[] temp = new int[9]; for(int m = 3*i; m < 3+3*i; m++){ for(int n = 3*j; n < 3+3*j; n++) { if(board[m][n] != ‘.‘){ temp[board[m][n] - ‘1‘]++; if(temp[board[m][n] - ‘1‘] > 1){ return false; } } } } } } return true; } }
Reference:
1. https://leetcode.com/discuss/52006/simple-java-solution-using-three-iterations-all-three-cases
标签:
原文地址:http://www.cnblogs.com/anne-vista/p/4865634.html