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 '.'.

Best Approach:

  • '4' in row 7 is encoded as "(4)7".
  • '4' in column 7 is encoded as "7(4)".
  • '4' in the top-right block is encoded as "0(4)2".
 1 public boolean isValidSudoku(char[][] board) {
 2     Set seen = new HashSet();
 3     for (int i=0; i<9; ++i) {
 4         for (int j=0; j<9; ++j) {
 5             if (board[i][j] != '.') {
 6                 String b = "(" + board[i][j] + ")";
 7                 if (!seen.add(b + i) || !seen.add(j + b) || !seen.add(i/3 + b + j/3))
 8                     return false;
 9             }
10         }
11     }
12     return true;
13 }

然后在解Sudoku Solver的时候,遇到了一个很简单的解法(但是这里不适用):

 1 public class Solution {
 2     public boolean isValidSudoku(char[][] board) {
 3         if (board == null || board.length != 9 || board[0].length != 9) return false;
 4         for (int i = 0; i < 9; i++) {
 5             for (int j = 0; j < 9; j++) {
 6                 if (board[i][j] == '.') continue;
 7                 if (!isvalid(board, i, j)) return false;
 8             }
 9         }
10         return true;
11     }
12     
13     public boolean isvalid(char[][] board, int i, int j) {
14         for (int a = 0; a < 9; a++) {
15             if (a != i && board[a][j] == board[i][j]) return false;
16         }
17         
18         for (int b = 0; b < 9; b++) {
19             if (b != j && board[i][b] == board[i][j]) return false; 
20         }
21         
22         for (int c = i/3*3; c < i/3*3 + 3; c++) {
23             for (int d = j/3*3; d < j/3*3 + 3; d++) {
24                 if ((c != i || d != j) && board[c][d] == board[i][j]) return false;
25             }
26         }
27         
28         return true;
29     }
30 }
原文地址:https://www.cnblogs.com/EdwardLiu/p/3719965.html