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

leetcode------Valid Sudoku

时间:2015-01-26 19:09:45      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:

标题: Valid Sudoku

通过率:

27.2%
难度: 简单

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.

 

这个题做了一天。。。。醉了。。。这个题目其实不难。

刚开始的时候我以为是求数独的解,给我吓一跳,简单题目都这么难了,然后我仔细一看就是求数独是否成立,那么就是满足三种情况

1、一列内不能有重复。

2、一行内不能重复。

3、一个3×3方格内不能有重复。

对于一行或者一列就是两重循环,但是对于求方格还是要画一下的。如下为九个方格的边界坐标(坐上到右下的遍历):

(0,0)→(2,2) (0,3)→(2,5) (0,6)→(2,8)
(3,0)→(5,2) (3,3)→(5,5) (3,6)→(5,8)
(6,0)→(8,2) (6,3)→(8,5) (6,6)→(8,8)

所以要写单独写一个函数去处理这个九个方格内的重复。

以上求解的方法主要用到了hashset去处理重复。具体代码如下:

 1 public class Solution {
 2     public boolean isValidSudoku(char[][] board) {
 3         Set<Character> set=new HashSet<Character>();
 4         int x=0,y=0;
 5         for(int i=0;i<9;i++){
 6             set.clear();
 7             for(int j=0;j<9;j++){
 8                 if(board[i][j]==‘.‘)continue;
 9                 if(set.contains(board[i][j]))return false;
10                 else
11                 set.add(board[i][j]);
12                 
13             }
14         }
15         for(int i=0;i<9;i++){
16             set.clear();
17             for(int j=0;j<9;j++){
18                 if(board[j][i]==‘.‘)continue;
19                 if(set.contains(board[j][i]))return false;
20                 else
21                 set.add(board[j][i]);
22             }
23         }
24         for(x=0;x<=6;x+=3){
25             for(y=0;y<=6;y+=3){
26                 if(!getRight(x,y,board))return false;
27             }
28         }
29         
30         return true;
31     }
32     public boolean getRight(int x,int y,char[][] board){
33         Set<Character> tmp=new HashSet<Character>();
34         int endx=x+3,endy=y+3,startx=x,starty=y;
35         tmp.clear();
36         for(x=startx;x<endx;x++)
37         for(y=starty;y<endy;y++){
38            if(board[x][y]==‘.‘)continue;
39             if(tmp.contains(board[x][y]))return false;
40             else
41             tmp.add(board[x][y]);
42         }
43         return true;
44     }
45 }

写了一天是因为再处理两重循环时,第二层循环每次都要从头开始,不能不去处理,在代码里就是每次循环y时都要把y=starty操作。

 

leetcode------Valid Sudoku

标签:

原文地址:http://www.cnblogs.com/pkuYang/p/4250959.html

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