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

LeetCode Valid Sudoku

时间:2015-01-09 00:03:00      阅读:259      评论: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 ‘.‘.

技术分享

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.

 

Sudoku规则:

在一个9*9的区域内,

每行1-9出现且只出现一次,

每列1-9出现且只出现一次,

在9个子3*3的区域内1-9出现且只出现一次。

 

 1 public class Solution {
 2     public boolean isValidSudoku(char[][] board) {
 3         ArrayList<HashSet<Integer>> row = new ArrayList<HashSet<Integer>>();
 4         ArrayList<HashSet<Integer>> col = new ArrayList<HashSet<Integer>>();
 5         ArrayList<HashSet<Integer>> box = new ArrayList<HashSet<Integer>>();
 6 
 7         for (int i = 0; i < 9; i++) {
 8             row.add(new HashSet<Integer>());
 9             col.add(new HashSet<Integer>());
10             box.add(new HashSet<Integer>());
11         }
12 
13         for (int i = 0; i < 9; i++) {
14             for (int j = 0; j < 9; j++) {
15                 if (board[i][j] == ‘.‘) {
16                     continue;
17                 }
18                 if (row.get(i).contains(board[i][j]-‘0‘)) {
19                     return false;
20                 } else row.get(i).add(board[i][j]-‘0‘);
21 
22                 if (col.get(j).contains(board[i][j] - ‘0‘)) {
23                     return  false;
24                 }else col.get(j).add(board[i][j] - ‘0‘);
25 
26                 int index = ((i / 3) * 3) + j / 3;
27                 if (box.get(index).contains(board[i][j] - ‘0‘)) {
28                     return false;
29                 }else box.get(index).add(board[i][j] - ‘0‘);
30             }
31         }
32 
33         return true;
34     }
35 }

 

LeetCode Valid Sudoku

标签:

原文地址:http://www.cnblogs.com/birdhack/p/4212152.html

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