Valid Sudoku

Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules
http://sudoku.com.au/TheRules.aspx .
The Sudoku board could be partially filled, where empty cells are filled with the character ‘.’.
这里写图片描述

#include <iostream>
#include <vector>

using namespace std;

class Solution
{
public:
    bool isValidSudoku(vector<vector<char>> &board)
    {
        bool visited[9];

        cout<<endl;
        for (int i=0; i < 9; ++i)
        {
            fill(visited,visited+9,false);

            for (int j=0; j < 9;++j)   //检查行
            {

                if(!check(board[i][j],visited))
                    return false;


            }



            fill(visited,visited+9,false);
            for (int j=0; j < 9;++j )   //检查列
            {
                if(!check(board[j][i],visited))
                    return false;
            }


        }

        //检查九宫格的每个子九宫格
        for (int i=0; i < 9; i+=3)
        {
            for (int j=0; j < 9; j+=3)
            {
                fill(visited,visited+9,false);

                for (int k=0; k < 9 ; ++k)
                {
                    bool chk=check(board[i+k/3][j+k%3],visited);
                     if (!chk)
                    {
                        return false;
                    }
                }
            }

        }

        return true;
    }

private:
    bool check(char ch, bool visited[9])
    {
        if (ch == '.')
            return true;
        if (visited[ch - '1'])
            return false;
        return visited[ch - '1'] = true;
    }
};

int main()
{
    vector<vector<char>> board = {{'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'}
                                 };
    for(auto it=board.cbegin(); it != board.cend(); ++it)
    {
        for(auto iter= (*it).cbegin(); iter != (*it).cend(); ++iter)
            cout<<*iter<<" ";
        cout<<endl;
    }
    cout<<endl;

    Solution solution;
    bool result = solution.isValidSudoku(board);
    cout<<boolalpha<<result<<endl;

    return 0;
}

这里写图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值