Valid Sudoku
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个九宫格里是否存在重复数字。
public class Solution { //判断一行或一列或9宫格里的9个数是否有重复 public boolean isValidRow(char[] row){ String str = ""; for(int i=0;i<9;i++){ if(row[i]!='.'){ if(!str.contains(String.valueOf(row[i]))){ str+=row[i]; } else{ return false; } } } return true; } //判断每行是否有重复数字 public boolean isValidLine(char[][] board){ for(int i=0;i<9;i++){ if(isValidRow(board[i])==false){ return false; } } return true; } //判断每列是否有重复数字 public boolean isValidColumn(char[][] board){ for(int i = 0;i < 9;i++){ char[] str = new char[9]; for(int j = 0;j <9;j++){ str[j] = board[j][i]; } if(isValidRow(str)==false){ return false; } } return true; } //判断每个九宫格里是否有重复数字 public boolean isValidSquare(char[][] board){ for(int i=0;i<=6;i=i+3){ int x = i; for(int j=0;j<=6;j=j+3){ char[] str = new char[9]; int y = j; for(int m=0;m<3;m++){ for(int n=0;n<3;n++){ str[m*3+n] = board[x+m][y+n]; } } if(isValidRow(str)==false){ return false; } } } return true; } public boolean isValidSudoku(char[][] board) { if(isValidLine(board)==false){ return false; } if(isValidColumn(board)==false){ return false; } if(isValidSquare(board)==false){ return false; } return true; } }