LeetCode_Valid Sudoku

一.题目

Valid Sudoku

  Total Accepted: 29804 Total Submissions: 109584My Submissions

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.

Show Tags
Have you met this question in a real interview?  
Yes
 
No

Discuss



















二.解题技巧

    这道题比较简单,就是遍历棋盘的所有位置,查看每一个位置上的元素是否满足Sudoku的要求,也就是每一行,每一列以及每个小9×9的区域是否存在相同的元素,如果存在相同的元素,即为不合法。对于判断一个元素是否在某一行,某一列或者某个小区域内,我的实现是将定义了9个整数代表每一列,9个整数代表每一行,9个元素代表了9个小的9×9的区域,因此,用每一个整数的第1到第九位表示某个元素是否在该列,该行或该小区域中。通过位操作可以判断该元素是否存在。


三.实现代码

#include <iostream>

#include <vector>

using namespace std;

class Solution
{
private:
    bool isExist(int &Input, int Number)
    {
        if (Input & (1 << Number))
        {
            return true;
        }

        Input =  Input | (1 << Number);
        return false;
    }


public:
    bool isValidSudoku(vector<vector<char> > &board)
    {
        int X_value[9] = {0};
        int Y_value[9] = {0};
        int Inside[9] = {0};

        for (int Index_y = 0; Index_y < 9; Index_y++)
        {
            vector<char> &TmpRow = board[Index_y];

            for (int Index_x = 0; Index_x < 9; Index_x++)
            {
                if (TmpRow[Index_x] == '.')
                {
                    continue;
                }

                int TmpValue = TmpRow[Index_x] - '0';

                // is valid in Index_x row
                if (isExist(X_value[Index_x], TmpValue))
                {
                    return false;
                }

                // is valid in Index_y col
                if (isExist(Y_value[Index_y], TmpValue))
                {
                    return false;
                }

                // is valid in 3*3 sub block
                if (isExist(Inside[Index_x / 3 + Index_y / 3 * 3] , TmpValue))
                {
                    return false;
                }
            }
        }

        return true;

    }
};





四.体会

    这道题基本上不需要什么算法,只是在考虑如何判断一个元素是否已经存在时需要稍微考虑下,我的实现用来27个整数的第1到第9位来判断一个元素是否已经存在。其实使用三个整数就基本上可以完成这样的任务了,只不过这样处理起来稍微有点复杂。
    这道题也算是一道水题,可以用于练练手。



版权所有,欢迎转载,转载请注明出处,谢谢微笑





  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值