【Leetcode】Valid Sudoku

题目链接:https://leetcode.com/problems/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.

思路:

每行、每列、每个黑粗线内小方块的数分别用HashSet保存判断是否唯一。

算法:

[java]  view plain  copy
 
  1. </pre><pre name="code" class="java">    public boolean isValidSudoku(char[][] board) {  
  2.         Set<Character> row = new HashSet<Character>();  
  3.         Set<Character> column = new HashSet<Character>();  
  4.         Set<Character> subBox = new HashSet<Character>();  
  5.   
  6.         for (int i = 0; i < board.length; i++) {  
  7.             for (int j = 0; j < board[0].length; j++) {  
  8.                 // System.out.print(board[i][j]+" ");  
  9.                 if (board[i][j] != '.') {  
  10.                     if (column.contains(board[i][j])) {  
  11.                         return false;  
  12.                     } else {  
  13.                         column.add(board[i][j]);  
  14.                     }  
  15.                 }  
  16.                 // System.out.println();  
  17.             }  
  18.             column.clear();  
  19.         }  
  20.   
  21.         // System.out.println("=============");  
  22.         for (int i = 0; i < board.length; i++) {  
  23.             for (int j = 0; j < board[0].length; j++) {  
  24.                 if (board[j][i] != '.') {  
  25.                     if (row.contains(board[j][i])) {  
  26.                         return false;  
  27.                     } else {  
  28.                         row.add(board[j][i]);  
  29.                     }  
  30.                 }  
  31.             }  
  32.             row.clear();  
  33.         }  
  34.   
  35.         for (int i = 0; i < board.length; i += 3) {  
  36.             for (int j = 0; j < board[0].length; j += 3) {  
  37.                 for (int ii = i; ii < i + 3; ii++) {  
  38.                     for (int jj = j; jj < j + 3; jj++) {  
  39.                         if (board[ii][jj] != '.') {  
  40.                             if (subBox.contains(board[ii][jj])) {  
  41.                                 return false;  
  42.                             } else {  
  43.                                 subBox.add(board[ii][jj]);  
  44.                             }  
  45.                         }  
  46.                     }  
  47.                 }  
  48.                 subBox.clear();  
  49.             }  
  50.         }  
  51.         return true;  
  52.     }  

你可能感兴趣的:(【Leetcode】Valid Sudoku)