首页 > 其他 > 详细

Leetcode-Valid Sudoku

时间:2014-11-29 08:51:09      阅读:177      评论:0      收藏:0      [点我收藏+]

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:

 1 public class Solution {
 2     public boolean isValidSudoku(char[][] board) {
 3         int rowNum = board.length;
 4         if (rowNum!=9) return false;
 5         int colNum = board[0].length;
 6         if (colNum!=9) return false;
 7 
 8         for (int i=0;i<rowNum;i++)
 9             if (!checkArea(board,i,0,1,9)) return false;
10   
11         for (int i=0;i<colNum;i++)
12             if (!checkArea(board,0,i,9,1)) return false;
13 
14         int[] index = new int[]{0,3,6};
15         for (int i=0;i<3;i++)
16             for (int j=0;j<3;j++)
17                 if (!checkArea(board,index[i],index[j],3,3)) return false;
18 
19         return true;
20        
21         
22     }
23 
24     public boolean checkArea(char[][] board, int x, int y, int rowNum, int colNum){
25         Set<Integer> set = new HashSet<Integer>();
26         for (int i=0;i<rowNum;i++)
27             for (int j=0;j<colNum;j++)
28                 if (board[x+i][y+j]!=‘.‘){
29                     int val = board[x+i][y+j]-‘0‘;
30                     if (val<0 || val>9) return false;
31                     if (set.contains(val))
32                         return false;
33                     else set.add(val);
34                 }
35 
36         return true;
37 
38     }
39                 
40 }

 

Leetcode-Valid Sudoku

原文:http://www.cnblogs.com/lishiblog/p/4129956.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!