在c++中,任何更好的方法都可以做到这一点,计算谜题的解决方案(49!结果,49个循环)

Any better way to do this in c++, calculating a solution to puzzle (49! outcomes, 49 loops)

本文关键字:解决方案 结果 循环 49个 这一点 更好 任何 c++ 方法 都可以 计算      更新时间:2023-10-16

这个谜题中基本上有49个瓦片。它们每个边缘都有4种颜色。我需要创建一个7x7拼图,其中一个瓷砖的每个边缘都与相邻瓷砖边缘的颜色相匹配,例如2x2解决方案:

       blue             purple
yellow     green  green       pink
       pink              blue
       pink              blue
purple     yellow yellow     green
       blue              pink

我打算给每种颜色分配数字,然后做一些类似(伪码)的事情:

for i in 1 to 49
    for j in 1 to 48
       if left colour of j == right colour of i
           join them
       for k in 1 to 47
           if left colour of k == right colour of j
.....
......

如果所有49个都已分配结束

我甚至不知道这么多次迭代是否可能,有什么建议吗?谢谢

4个正方形的示例图像(真正的谜题是49个正方形)https://i.stack.imgur.com/6ISpQ.png

只有当你真的想要真正的馅饼时才阅读:

真正的谜题被称为"神奇的方块拼图"

https://i.stack.imgur.com/K0MBl.jpg

我打算给甲虫的每一半分配一个小数,这样加在一起就等于1。然后我会像上面那样迭代,并检查添加时它们是否==1。

我认为您需要的是深度优先搜索算法。

每个瓦片的颜色可以用enum:表示

enum class TileColor {
    Blue,
    Purple,
    Yellow,
    Green,
    // ...
};

然后你可以用一个类来表示每个瓦片:

struct Tile {
    TileColor up;
    TileColor down;
    TileColor left;
    TileColor right;
};

然后在主过程中,你可以初始化一个7*7的拼图板,比如:

int main() {
    // To define a 7*7 board, vector is recommended.
    std::vector<std::vector<Tile> > board(7, std::vector<Tile>(7));
    // You can loop the vector in a traditional way like:
    for (auto row = 0; row < board.size(); ++row) {
        for (auto col = 0; col < board[row].size(); ++col) {
            // Some code here.
            // To assign a value to a tile, the code looks like:
            // board[row][col].left = TileColor::Blue;
            // To test color is match, the code looks like:
            // if (board[row][col].right == (board[row][col + 1].left) { ... }
            // The boundary condition is also needed to be considered here.
        }
    }
    // To loop in a more "C++" way, you could use iterator:
    for (auto row = board.begin(); row != board.end(); ++row) {
        for (auto col = row->begin(); col != row->end(); ++col) {
            // Some code here.
            // To assign a value to a tile, the code looks like:
            // col->left = TileColor::Blue;
            // To test color is match, the code looks like:
            // if (col->right == (col + 1)->left) { ... }
            // The boundary condition is also needed to be considered here.
        }
    }
    return 0;
}

然而,上面只是简单解释了关于基本数据类型的问题,对于解决该问题的算法来说,DFS将是一个合适的算法。更具体地说,您可能希望使用vector<Tile> tiles(7*7);来存储从输入文件或控制台读取的所有磁贴,然后在循环中,您尝试从tiles中提取一个磁贴并将其放在board上,然后检查它是否与其他磁贴匹配。如果匹配,循环将继续拾取下一个磁贴。如果不匹配,则从板上取下瓦片并将其放回tiles,返回到以前的状态。如果你所有的瓷砖都放在木板上,那么解决方案就出来了。

还有一个提示是,对于7*7的问题,您可能需要使用9*9板,其中为您添加了两行和两列,就像板上的板一样。

相关文章: