C++实现LeetCode(36.验证数独)

[LeetCode] 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-9without 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 '.'.

Example 1:

Input:

[

     ["5","3",".",".","7",".",".",".","."], 

     ["6",".",".","1","9","5",".",".","."],

     [".","9","8",".",".",".",".","6","."],

     ["8",".",".",".","6",".",".",".","3"],

     ["4",".",".","8",".","3",".",".","1"],

     ["7",".",".",".","2",".",".",".","6"],

     [".","6",".",".",".",".","2","8","."],

     [".",".",".","4","1","9",".",".","5"], 

     [".",".",".",".","8",".",".","7","9"]

]

Output: true

Example 2:

Input:

[

    ["8","3",".",".","7",".",".",".","."],

    ["6",".",".","1","9","5",".",".","."],

    [".","9","8",".",".",".",".","6","."],

    ["8",".",".",".","6",".",".",".","3"],

    ["4",".",".","8",".","3",".",".","1"],

    ["7",".",".",".","2",".",".",".","6"],

    [".","6",".",".",".",".","2","8","."],

    [".",".",".","4","1","9",".",".","5"],

    [".",".",".",".","8",".",".","7","9"]

]

Output: false

Explanation: Same as Example 1, except with the 5 in the top left corner being

modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid.

Note:

  • A Sudoku board (partially filled) could be valid but is not necessarily solvable.
  • Only the filled cells need to be validated according to the mentioned rules.
  • The given board contain only digits 1-9and the character '.'.
  • The given board size is always 9x9.

这道题让验证一个方阵是否为数独矩阵,想必数独游戏我们都玩过,就是给一个 9x9 大小的矩阵,可以分为9个 3x3 大小的矩阵,要求是每个小矩阵内必须都是1到9的数字不能有重复,同时大矩阵的横纵列也不能有重复数字,是一种很经典的益智类游戏,经常在飞机上看见有人拿着纸笔在填数,感觉是消磨时光的利器。这道题给了一个残缺的二维数组,让我们判断当前的这个数独数组是否合法,即要满足上述的条件。判断标准是看各行各列是否有重复数字,以及每个小的 3x3 的小方阵里面是否有重复数字,如果都无重复,则当前矩阵是数独矩阵,但不代表待数独矩阵有解,只是单纯的判断当前未填完的矩阵是否是数独矩阵。那么根据数独矩阵的定义,在遍历每个数字的时候,就看看包含当前位置的行和列以及 3x3 小方阵中是否已经出现该数字,这里需要三个 boolean 型矩阵,大小跟原数组相同,分别记录各行,各列,各小方阵是否出现某个数字,其中行和列标志下标很好对应,就是小方阵的下标需要稍稍转换一下,具体代码如下:

解法一:

class Solution {
public:
    bool isValidSudoku(vector<vector<char>>& board) {
        vector<vector<bool>> rowFlag(9, vector<bool>(9));
        vector<vector<bool>> colFlag(9, vector<bool>(9));
        vector<vector<bool>> cellFlag(9, vector<bool>(9));
        for (int i = 0; i < 9; ++i) {
            for (int j = 0; j < 9; ++j) {
                if (board[i][j] == '.') continue;
                int c = board[i][j] - '1';
                if (rowFlag[i][c] || colFlag[c][j] || cellFlag[3 * (i / 3) + j / 3][c]) return false;
                rowFlag[i][c] = true;
                colFlag[c][j] = true;
                cellFlag[3 * (i / 3) + j / 3][c] = true;
            }
        }
        return true;
    }
};

我们也可以对空间进行些优化,只使用一个 HashSet 来记录已经存在过的状态,将每个状态编码成为一个字符串,能将如此大量信息的状态编码成一个单一的字符串还是需要有些技巧的。对于每个1到9内的数字来说,其在每行每列和每个小区间内都是唯一的,将数字放在一个括号中,每行上的数字就将行号放在括号左边,每列上的数字就将列数放在括号右边,每个小区间内的数字就将在小区间内的行列数分别放在括号的左右两边,这样每个数字的状态都是独一无二的存在,就可以在 HashSet 中愉快地查找是否有重复存在啦,参见代码如下:

解法二:

class Solution {
public:
    bool isValidSudoku(vector<vector<char>>& board) {
        unordered_set<string> st;
        for (int i = 0; i < 9; ++i) {
            for (int j = 0; j < 9; ++j) {
                if (board[i][j] == '.') continue;
                string t = "(" + to_string(board[i][j]) + ")";
                string row = to_string(i) + t, col = t + to_string(j), cell = to_string(i / 3) + t + to_string(j / 3);
                if (st.count(row) || st.count(col) || st.count(cell)) return false;
                st.insert(row);
                st.insert(col);
                st.insert(cell);
            }
        }
        return true;
    }
};

到此这篇关于C++实现LeetCode(36.验证数独)的文章就介绍到这了,更多相关C++实现验证数独内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • C++实现LeetCode(28.实现strStr()函数)

    [LeetCode] 28. Implement strStr() 实现strStr()函数 Implement strStr(). Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Example 1: Input: haystack = "hello", needle = "ll" Output: 2 E

  • C++实现LeetCode(37.求解数独)

    [LeetCode] 37. Sudoku Solver 求解数独 Write a program to solve a Sudoku puzzle by filling the empty cells. A sudoku solution must satisfy all of the following rules: Each of the digits 1-9 must occur exactly once in each row. Each of the digits 1-9 must

  • C++实现LeetCode(33.在旋转有序数组中搜索)

    [LeetCode] 33. Search in Rotated Sorted Array 在旋转有序数组中搜索 Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). You are given a target value to search. If f

  • C++实现LeetCode(32.最长有效括号)

    [LeetCode] 32. Longest Valid Parentheses 最长有效括号 Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. Example 1: Input: "(()" Output: 2 Explanation: The longest valid

  • C++实现LeetCode(31.下一个排列)

    [LeetCode] 31. Next Permutation 下一个排列 Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sor

  • C++实现LeetCode(29.两数相除)

    [LeetCode] 29. Divide Two Integers 两数相除 Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator. Return the quotient after dividing dividend by divisor. The integer division should truncate

  • C++实现LeetCode(30.串联所有单词的子串)

    [LeetCode] 30. Substring with Concatenation of All Words 串联所有单词的子串 You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words ex

  • C++实现LeetCode(36.验证数独)

    [LeetCode] 36. Valid Sudoku 验证数独 Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules: Each row must contain the digits 1-9without repetition. Each column must contain the digits 1-9 wi

  • C++实现LeetCode(9.验证回文数字)

    [LeetCode] 9. Palindrome Number 验证回文数字 Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. Example 1: Input: 121 Output: true Example 2: Input: -121 Output: false Explanation: From left

  • C++实现LeetCode(20.验证括号)

    [LeetCode] 20. Valid Parentheses 验证括号 Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open

  • C++实现LeetCode(98.验证二叉搜索树)

    [LeetCode] 98. Validate Binary Search Tree 验证二叉搜索树 Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The ri

  • Pipes实现LeetCode(193.验证电话号码)

    [LeetCode] 193.Valid Phone Numbers 验证电话号码 Given a text file file.txt that contains list of phone numbers (one per line), write a one liner bash script to print all valid phone numbers. You may assume that a valid phone number must appear in one of th

  • C++实现LeetCode(125.验证回文字符串)

    [LeetCode] 125.Valid Palindrome 验证回文字符串 Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. For example, "A man, a plan, a canal: Panama" is a palindrome. "race a car" is not a

  • IntelliJ IDEA 刷题利器 LeetCode 插件详解

    IDEA整合LeetCode插件,可以在 IDEA 本地编辑代码并且运行提交,还能关联自己的账号,非常实用. 下载安装 配置 点击File->Settings->Tools->leetcode plugin,如图: 参数说明: Custom code template: 开启使用自定义模板,否则使用默认生成格式 CodeFileName: 生成文件的名称,默认为题目标题 CodeTemplate: 生成题目代码的内容,默认为题目描述和题目代码 TemplateConstant: 模板常用

  • Python实现"验证回文串"的几种方法

    一.LeetCode--125.验证回文串 1.问题描述 给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写. 说明:本题中,我们将空字符串定义为有效的回文串. 2.示例 示例 1: 输入: "A man, a plan, a canal: Panama" 输出: True 示例 1: 输入: "race a car" 输出: False 示例 3: 输入: "!!!" 输出: True 二.解题分析 在排除空格及特殊

  • Java栈的应用之括号匹配算法实例分析

    本文实例讲述了Java栈的应用之括号匹配算法.分享给大家供大家参考,具体如下: 1.LeetCode官网 美网:https://leetcode.com/ 中文网 :https://leetcode-cn.com/ 英语不咋地,所以选择此处选择中文网来进行测试. 2.LeetCode中获取第20号题目 (1)搜索20号题目 (2)查看题目 (3)根据题目要求,首先在本地编辑器中完善20号题目的代码--使用java提供的Stack类,代码如下: class Solution { public bo

随机推荐