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

Leetcode-Valid Sudoku

时间:2014-11-29 08:53:32      阅读:168      评论:0      收藏:0      [点我收藏+]

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

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

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

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

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