检查数独解决方案是否有效 [英] Check if Sudoku solution is valid

查看:46
本文介绍了检查数独解决方案是否有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您获得了一个数独谜题的解决方案.编写代码以检查它是否是一个有效的解决方案.

You're given a solution to a Sudoku puzzle. Write the code to check if it's a valid solution.

你的函数签名应该是:
boolean isValid(int starti, int startj, int endi, int endj)

不熟悉数独的规则:

  • 网格大小为 9x9,分为 9 个 3x3 的区域
  • 每行必须包含 1-9 的所有数字
  • 每列必须包含 1-9 的所有数字
  • 每个 3x3 方格必须包含 1-9 的所有数字

我没有被问到这个问题,但在 几个 地点.检查最后一条规则可能是有趣的部分

I wasn't asked this question, but saw it on several places. Checking the last rule might be the interesting part

推荐答案

// rows
for (int i=0; i<9; i++) {
    std::bitset<9> filled;
    for (int j=0; j<9; j++)
        filled.set(grid[i][j] - 1);
    if (filled.count() != 9)
        return false;
}

// ... similar with the loops "swapped" to get the columns
// (or do both in one loop)

for (int i=0; i<9; i += 3)
    for (int j=0; j<9; j += 3) {
        std::bitset<9> filled;
        for (int k=0; k<3; k++)
            for (int l=0; l<3; l++)
                filled.set(grid[i+k][j+l] - 1);
        if (filled.count() != 9)
            return false;
    }

return true;

这篇关于检查数独解决方案是否有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆