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.

     1 class Solution {
     2 public:
     3     bool isValidSudoku(const vector<vector<char>>& board) {
     4         bool used[9];
     5         for (int i = 0; i < 9; ++i) {
     6             memset(used, false, 9);
     7             for (int j = 0; j < 9; ++j) {
     8                 if (board[i][j] == '.') continue;
     9                 if (used[board[i][j] - '1']) {
    10                     return false;
    11                 } else {
    12                     used[board[i][j] - '1'] = true;
    13                 }
    14             }
    15             memset(used, false, 9);
    16             for (int j = 0; j < 9; ++j) {
    17                 if (board[j][i] == '.') continue;
    18                 if (used[board[j][i] - '1']) {
    19                     return false;
    20                 } else {
    21                     used[board[j][i] - '1'] = true;
    22                 }
    23             }
    24         }
    25         for (int r = 0; r < 3; ++r) {
    26             for (int c = 0; c < 3; ++c) {
    27                 memset(used, false, 9);
    28                 for (int i = 0; i < 3; ++i) {
    29                     for (int j = 0; j < 3; ++j) {
    30                         int v1 = r * 3 + i;
    31                         int v2 = c * 3 + j;
    32                         if (board[v1][v2] == '.') continue;
    33                         if (used[board[v1][v2] - '1']) {
    34                             return false;
    35                         } else {
    36                             used[board[v1][v2] - '1'] = true;
    37                         }
    38                     }
    39                 }
    40             }
    41         }
    42         return true;
    43     }
    44 };
    View Code

    依次检查即可,开始自作聪明想要在一个大的循环里面把三种方式都检查了,但是发现在检查小方块时下标运算会有除法和求模,反而使得程序变慢,另列一个3*3的循环虽然使代码变得复杂一点,但是思路清晰,且速度更快。

  • 相关阅读:
    洛谷1894 [USACO4.2]完美的牛栏The Perfect Stall
    洛谷2417 课程
    洛谷2860 [USACO06JAN]冗余路径Redundant Paths
    洛谷1983 车站分级
    BZOJ1178或洛谷3626 [APIO2009]会议中心
    BZOJ1179或洛谷3672 [APIO2009]抢掠计划
    CF Round #516 (Div. 2, by Moscow Team Olympiad)
    洛谷1262 间谍网络
    NOI导刊 2018河南郑州游记
    BZOJ1001或洛谷4001 [BJOI2006]狼抓兔子
  • 原文地址:https://www.cnblogs.com/dengeven/p/3611281.html
Copyright © 2011-2022 走看看