LeetCode Valid Sudoku

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 }
原文地址:https://www.cnblogs.com/birdhack/p/4212152.html