码迷,mamicode.com
首页 > 其他好文 > 详细

[Leetcode] Valid Sudoku

时间:2014-11-17 17:18:49      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   ar   sp   for   div   

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 ‘.‘.

bubuko.com,布布扣

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.
bubuko.com,布布扣
Each column must have the numbers 1-9 occuring just once.
 
 
 
 
 
 
 
bubuko.com,布布扣
And the numbers 1-9 must occur just once in each of the 9 sub-boxes of the grid.
bubuko.com,布布扣

 

一个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 }

 

[Leetcode] Valid Sudoku

标签:style   blog   http   io   color   ar   sp   for   div   

原文地址:http://www.cnblogs.com/Phoebe815/p/4103688.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!