[leetcode]36. Valid Sudoku验证数独

Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:

  1. Each row must contain the digits 1-9 without repetition.
  2. Each column must contain the digits 1-9 without repetition.
  3. Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition.

The Sudoku board could be partially filled, where empty cells are filled with the character '.'.

题意:

验证数独

思路:

用char[] map = new char[256] 作为一件简化版的hashmap

扫row、col、box

当前数字c若没在map里出现,则map[c] ++; 若在map里出现过,说明有重复,则返回false。

       

代码:

 1 public class ValidSudoku {
 2     public boolean isValidSudoku(char[][] board) {
 3         // corner case
 4         if (board == null || board.length != 9 || board[0].length != 9)
 5             return false;
 6         //row
 7         for (int row = 0; row < 9; row++) {
 8             char[] map = new char[256];
 9             for (int i = 0; i < 9; i++) {
10                 char c = board[row][i];
11                 if (c != '.') {
12                     if (map[c] > 0) {
13                         return false;
14                     } else {
15                         map[c]++;
16                     }
17                 }
18             }
19         }
20         // col
21         for (int col = 0; col < 9; col++) {
22             char[] map = new char[256];
23             for (int i = 0; i < 9; i++) {
24                 char c = board[i][col];
25                 if (c != '.') {
26                     if (map[c] > 0) {
27                         return false;
28                     } else {
29                         map[c]++;
30                     }
31 
32                 }
33             }
34         }
35         //box
36         for (int box = 0; box < 9; box++) {
37             char[] map = new char[256];
38             for (int row = 0; row < 3; row++) {
39                 for (int col = 0; col < 3; col++) {
40                     char c = board[row + 3 * (box / 3)][col + 3 * (box % 3)];
41                     if (c != '.') {
42                         if (map[c] > 0) {
43                             return false;
44                         } else {
45                             map[c]++;
46                         }
47 
48                     }
49 
50                 }
51 
52             }
53 
54         }
55         return true;
56     }
57 }

猜你喜欢

转载自www.cnblogs.com/liuliu5151/p/9142872.html