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

    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.


    解题思路:

    首先检查是否是9*9 矩阵;

    其次依次检查每行,每列和内部各个3*3 矩阵是否满足要求。

    建立int[] temp, temp.length = 9 来存储1-9 的个数,当temp[i] > 1时,说明有重复数字出现,返回false.


    Java code:

    public class Solution {
        public boolean isValidSudoku(char[][] board) {
           if(board == null || board.length !=9 || board[0].length != 9){
               return false;
           }
           //check each row
           for(int i = 0; i < 9; i++){
               int[] temp = new int[9];
               for(int j = 0; j < 9; j++){
                   if(board[i][j] != '.'){
                       temp[board[i][j] - '1']++;
                       if(temp[board[i][j] - '1'] > 1){
                           return false;
                       }
                   }
               }
           }
           //check each column
           for(int j = 0; j < 9; j++){
               int[] temp = new int[9];
               for(int i = 0; i < 9; i++){
                   if(board[i][j] != '.'){
                       temp[board[i][j] - '1']++;
                       if(temp[board[i][j] - '1'] > 1){
                           return false;
                       }
                   }
               }
           }
           //check each 3*3 matrix
           for(int i = 0; i < 3; i++) {
               for(int j = 0; j < 3; j++){
                   int[] temp = new int[9];
                   for(int m = 3*i; m < 3+3*i; m++){
                       for(int n = 3*j; n < 3+3*j; n++) {
                           if(board[m][n] != '.'){
                               temp[board[m][n] - '1']++;
                               if(temp[board[m][n] - '1'] > 1){
                                   return false;
                               }
                           }
                       }
                   }
               }
           }
           return true;
        }
    }

    Reference:

    1. https://leetcode.com/discuss/52006/simple-java-solution-using-three-iterations-all-three-cases

  • 相关阅读:
    Silverlight 4 新特性之NotificationWindow
    如何理解JavaScript原型
    惹恼程序员的十件事
    浅谈HTTP中Get与Post的区别
    asp中Access与Sql Server数据库区别总结
    SQL208语句
    jQuery源码分析
    3. 在 as 和 强制类型转换之间,优先使用 as 操作符。
    揭秘10项必学的.NET技术
    如何设置远程访问SQL Server2005
  • 原文地址:https://www.cnblogs.com/anne-vista/p/4865634.html
Copyright © 2011-2022 走看看