首页 > 代码库 > [Leetcode] Valid Sudoku
[Leetcode] 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.
Solution:
There are just 3 rules to Sudoku. | |
Each row must have the numbers 1-9 occuring just once. | |
Each column must have the numbers 1-9 occuring just once. | |
And the numbers 1-9 must occur just once in each of the 9 sub-boxes of the grid. |
一个valid的sudoku只有3个条件:横、竖、小方块内部 满足条件即可。
我老想成还需要对角线上的数也满足条件,这样想是错的!!!
1 public class Solution { 2 public boolean isValidSudoku(char[][] board) { 3 for(int i=0;i<board.length;++i){ 4 for(int j=0;j<board[0].length;++j){ 5 if(board[i][j]==‘.‘){ 6 continue; 7 }else{ 8 char temp=board[i][j]; 9 board[i][j]=‘C‘; //通过将board[i][j]的值改为board内部的其他位置的数10 boolean b=isValid(board,i,j,temp); //不可能取到的值来方便后边儿的验证。11 board[i][j]=temp;12 if(b==false)13 return false;14 }15 }16 }17 return true;18 }19 20 private boolean isValid(char[][] board, int x, int y, char temp) {21 // TODO Auto-generated method stub22 for(int i=0;i<board.length;++i){ //竖着的23 if(board[i][y]==temp)24 return false;25 }26 for(int i=0;i<board[0].length;++i){ //横着的27 if(board[x][i]==temp){28 return false;29 }30 }31 for(int i=(x/3)*3;i<(x/3+1)*3;++i){ //小方块内部的32 for(int j=(y/3)*3;j<(y/3+1)*3;++j){ //判断好属于哪块小方格33 if(board[i][j]==temp)34 return false;35 }36 }37 return true;38 }39 }
[Leetcode] Valid Sudoku
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。