zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    Advanced Installer文件和文件夹页面中的临时文件操作
    celery使用方法
    网站高并发之道
    大话程序猿眼里的高并发
    StringTokenizer类的使用
    linux下查看最消耗CPU、内存的进程
    分享10条PHP性能优化的小技巧,帮助你更好的用PHP开发:
    json 除去转义字符以及查看json错误
    关于 redis、memcache、mongoDB 的对比
    QPS 与 TPS 简介
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/3719965.html
Copyright © 2011-2022 走看看