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


    A partially filled sudoku which is valid.

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

    思考:先检查每一行,再检查每一列,最后检查9个子方块,时间复杂度为n2+n2+n2=O(n2)。

     1 class Solution {
     2 public:
     3     bool isValidSudoku(vector<vector<char>>& board) {
     4         int map[10] ={0};
     5         int i,j;
     6         //row
     7         for(i=0; i<9; i++) {
     8             memset(map,0,10*sizeof(int));
     9             for(j=0;j<9;j++){
    10                 if(board[i][j]=='.') continue;
    11                 if(map[board[i][j]-'0']) return false;
    12                 map[board[i][j]-'0'] = 1;
    13             }     
    14         }
    15         //column
    16         for(j=0; j<9; j++) {
    17             memset(map,0,10*sizeof(int));
    18             for(i=0; i<9; i++) {
    19                  if(board[i][j]=='.') continue;
    20                 if(map[board[i][j]-'0']) return false;
    21                 map[board[i][j]-'0'] = 1;
    22             }
    23         }
    24        //3x3 subbox
    25         for(i=0; i<9; i=i+3) {
    26             for(j=0; j<9; j=j+3) {
    27                 memset(map, 0, 10*sizeof(int));
    28                 for(int m=i; m<i+3; m++) {
    29                     for(int n=j; n<j+3; n++) {
    30                         if(board[m][n]=='.') continue;
    31                         if(map[board[m][n]-'0']) return false;
    32                         map[board[m][n]-'0'] = 1;
    33                     }
    34                 }
    35             }
    36         }
    37 
    38         return true;
    39         
    40     }
    41 };
  • 相关阅读:
    java 编译
    MapReduce
    搜索引擎中index、attribute和summary概念
    正排索引和倒排索引简单介绍
    SVN 使用
    PlantUML + Chrome 联合使用
    vim 多标签和多窗口
    关于数据库不适合docker的原因(摘抄)
    跨域
    is_valid校验机制
  • 原文地址:https://www.cnblogs.com/midhillzhou/p/9079065.html
Copyright © 2020-2023  润新知