在c++中,任何更好的方法都可以做到这一点,计算谜题的解决方案(49!结果,49个循环)
Any better way to do this in c++, calculating a solution to puzzle (49! outcomes, 49 loops)
这个谜题中基本上有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
板,其中为您添加了两行和两列,就像板上的板一样。
- 运行同一解决方案的另一个项目的项目
- Project Euler问题4的错误解决方案
- 计算每个节点的树高,帮助我解释这个代码解决方案
- C++:Application.cpp中抛出了未解析的外部符号(解决方案在问题的末尾,供未来的读者参考)
- visual c++,如何获取解决方案目录中的代码
- 有没有办法在远程设备上打开和编辑visual Studio 2017解决方案
- C++Matching Brackets 2解决方案不起作用
- 在 ubuntu3 上C++ goto 定义有什么解决方案吗16.04?
- 在 leetcode 上提交解决方案时出现堆栈缓冲区溢出错误
- 我的固定时间步长与增量时间和插值的解决方案是错误的吗?
- 无法在问题解决方案中执行输出逻辑
- 最大的回文产品 - 程序未运行,编写解决方案但无法理解问题
- 从预序遍历构造 bst 的 c++ 和 python 解决方案之间的区别
- 在一个解决方案中针对第三方静态库 (Creo) 的不同版本(版本)进行构建
- 如何巧妙地编写两个函数——一个用于检查是否存在解决方案,另一个用于获取所有解决方案
- 使用 Git 处理 C++ Visual Studio 2019 解决方案的外部依赖项源代码管理的最佳方法是什么?
- N-queen问题:无法弄清楚为什么我的解决方案不起作用
- 为什么我的 Go 解决方案给出的结果与C++不同
- (欧拉计划#3)试图将Python中的解决方案复制到C++,结果非常糟糕,不知道如何
- 在c++中,任何更好的方法都可以做到这一点,计算谜题的解决方案(49!结果,49个循环)