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 };
  • 相关阅读:
    【java基础学习一】int[]、Integer[]、String[] 排序( 正序、倒叙)、去重
    【转】jqGrid 各种参数 详解
    CSS 中文字体的英文名称 (simhei, simsun) 宋体 微软雅黑
    Web应用程序项目XX已配置为使用IIS
    zsh安装及配置
    vscode安装及配置
    matlab2018a安装及配置
    teminator安装及配置
    clion安装及配置
    pcl之octree的使用
  • 原文地址:https://www.cnblogs.com/alway6s/p/3782867.html
Copyright © 2011-2022 走看看