判断数独是否合法-LintCode

请判定一个数独是否有效。
该数独可能只填充了部分数字,其中缺少的数字用 . 表示。

注意事项:
一个合法的数独(仅部分填充)并不一定是可解的。我们仅需使填充的空格有效即可。

说明:
什么是 数独?
http://sudoku.com.au/TheRules.aspx
http://baike.baidu.com/subview/961/10842669.htm

样例:
这里写图片描述
The following partially filed sudoku is valid.

#ifndef C389_H
#define C389_H
#include<iostream>
#include<vector>
#include<map>
using namespace std;
class Solution {
public:
    /*
    * @param board: the board
    * @return: whether the Sudoku is valid
    */
    bool isValidSudoku(vector<vector<char>> &board) {
        // write your code here
        int m = board.size();
        int n = board[0].size();
        map<char, int> count;
        for (int i = 0; i < m; ++i)
        {
            count.clear();
            for (int j = 0; j < n; ++j)
            {
                if (isdigit(board[i][j]))
                {
                    if (count.find(board[i][j]) == count.end())
                    {
                        count[board[i][j]]++;
                    }
                    else
                    {
                        return false;
                        break;
                    }
                }
            }
        }
        for (int j = 0; j < n; ++j)
        {
            count.clear();
            for (int i = 0; i < m; ++i)
            {
                if (isdigit(board[i][j]))
                {
                    if (count.find(board[i][j]) == count.end())
                    {
                        count[board[i][j]]++;
                    }
                    else
                    {
                        return false;
                        break;
                    }
                }
            }
        }
        vector<vector<int>> dir{ { 0, 0 }, { -1, 0 }, { -1, -1 }, { 0, -1 }, { 1, -1 }, { 1, 0 }, { 1, 1 }, { 0, 1 }, { -1, 1 } };
        vector<vector<int>> center{ { 1, 1 }, { 1, 4 }, { 1, 7 }, { 4, 1 }, { 4, 4 }, { 4, 7 }, { 7, 1 }, { 7, 4 }, { 7, 7 } };
        for (auto c : center)
        {
            count.clear();
            for (auto t : dir)
            {
                int x = c[0] + t[0];
                int y = c[1] + t[1];
                if (isdigit(board[x][y]))
                {
                    if (count.find(board[x][y]) == count.end())
                    {
                        count[board[x][y]]++;
                    }
                    else
                    {
                        return false;
                        break;
                    }
                }
            }
        }
        return true;
    }
};
#endif
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值