c++ - 如何清理这些嵌套的 for 循环?

标签 c++

<分区>

注意:前面有错误代码。您已收到警告。

此代码遍历数独游戏中所有 3x3 方 block 中的所有元素。下面显示的方法是获取每个正方形左上角元素的坐标,然后遍历该正方形中的每个元素。这意味着总共需要 4 个“for”循环才能访问正确的索引,然后另一个“for”循环才能执行正确的操作。

这段代码可以工作(如果收回的代码被放入),但它看起来非常困惑并且很难阅读。有没有更好的方法来消除这些嵌套的“for”循环?

提前致谢。

void Sudoku::updateSquares(int grid[9][9], int possibleSolutions[9][9][10])
{
    for (int i = 0; i < 9; i += 3)
    {
        for (int j = 0; j < 9; j += 3)      //for every square:
        {
                            //Other code
                            //...
                            //Other code

            //updates the possibleSolutions array
            for (int k = 0; k < 3; k++)
            {
                for (int l = 0; l < 3; l++)    //for every element in every square:
                {
                    if(grid[i+k][j+l] != 0)
                        continue;
                    for (int n = 0; n < 10; n++)
                    {
                        if(possibleSolutions[i+k][j+l][n] != 0 && numbers[n] == 0)
                        {
                            possibleSolutions[i+k][j+l][n] = 0;
                            possibleSolutions[i+k][j+l][0] -= 1;  //reduce the size, which is held in [][][0]
                        }
                    }
                }
            }

        }
    }
}

最佳答案

您已经实现了一种称为“详尽搜索”的方法,它实际上是在尝试所有可能的方 block 组合。

  1. 您听说过一种叫做循环展开的东西吗?

    --> 多次使​​用更少的嵌套循环,而不是 5 个嵌套的 For 循环;类似于 2 个嵌套循环。

  2. 使用可能是 O(n^2) 的动态规划方法

Top Coder DP example.

关于c++ - 如何清理这些嵌套的 for 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19349832/

相关文章:

c++ - 正在尝试解决链接器警告 : defaultlib 'MSVCRT' conflicts with use of other libs

c++ - “Node”仅在一个源文件C++中模棱两可

c++ - 将非模板基类向下转换为非类型模板子类

c++ - boost::asio 无法完全关闭 TCP 连接

c++ - Libcurl - 使用真实名称下载和保存文件

c++ - CDocument::SetPathName 在 WinXp 和 Windows 7 中的行为不同

c++ - Windows 的 SetEvent 的确切行为是什么?

c++ - static lock_guard 和 static mutex 也一样吗?

c++ - 如何在声明后设置 const char*?

c++ - typeid() 可以用来传递函数吗?