[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 stub
22         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 }
原文地址:https://www.cnblogs.com/Phoebe815/p/4103688.html