zoukankan      html  css  js  c++  java
  • LeetCode Valid Sudoku

    思路:

    对某一个有数字的格子检查是否valid,就是从行、列、宫三个方面来检查,检查的标准就是除了该格子,行、列、宫内的其他8个格子是否包含这个数字。那么实现就用两个循环,来逐行逐列的遍历,如果对应的格子里面有数字,那么就进行检查,否则扫描下一个格子。

     1 /*
     2     Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules:http://sudoku.com.au/TheRules.aspx.
     3     The Sudoku board could be partially filled, where empty cells are filled with the character '.'.
     4     Note:
     5     A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
     6 
     7     Copyright ©2014 Vincent Zhang 
     8     Blog: http://www.centvin.com 
     9 */
    10 class Solution {
    11 public:
    12     bool isValidSudoku(vector<vector<char> > &board) {
    13         for (int row=0; row< BOARD_SIZE; row++) {
    14             for (int col=0; col<BOARD_SIZE; col++) {
    15                 if (board[row][col] != '.') {
    16                     if (!isValid(board, row, col))
    17                         return false;
    18                 }
    19             }
    20         }
    21         return true;
    22     }
    23 private:
    24     bool isValid(vector<vector<char> > &board, int row, int col) {
    25         char curChar = board[row][col];
    26         // check the row and col
    27         for (int i=0;i<BOARD_SIZE;i++) {
    28             if (curChar == board[row][i] && i != col)        // row check
    29                 return false;
    30             if (curChar == board[i][col] && i != row)        // col check
    31                 return false;
    32         }
    33         // check the sub block
    34         int blockStartRow = (row / 3)*3;
    35         int blockStartCol = (col / 3)*3;
    36 
    37         for (int i=blockStartRow;i<blockStartRow+3;i++) {
    38             for (int j=blockStartCol; j<blockStartCol+3; j++) {
    39                 if (curChar == board[i][j] && i != row && j != col) 
    40                     return false;
    41             }
    42         }
    43         return true;
    44     }
    45     static const int BOARD_SIZE = 9;
    46     static const int BLOCK_SIZE = 3;
    47 };
  • 相关阅读:
    使用 %matplotlib inline 出错?
    RandomForest 调参
    sql中的笛卡尔积
    Sublime text 3 搭建Python3 IDE
    在Windows Python3.5 安装LightGBM
    lodash获取数组或对象的值 at
    lodash 移除数据元素 pull without 删除数组元素
    js 常用类型转换简写
    UTC时间格式转换
    CSS Flexible 布局兼容性以及解决方案
  • 原文地址:https://www.cnblogs.com/alway6s/p/3782867.html
Copyright © 2011-2022 走看看