对象的广度优先遍历
我正在编写一个解决益智游戏的程序,它会找到棋盘上所有可能的动作,并将所有可能的结果棋盘放入一个对象中。然后它会找到结果棋盘的所有可能的走法,依此类推。该对象看起来像这样:
{
"board": {
"starts": [[0,0],[0,3]],
"blocks": [[3,0],[3,3]],
"ends": [[2,4]]
},
"possibleMoves": [
{
"board": {
"starts": [[0,0],[2,3]],
"blocks": [[3,0],[3,3]],
"ends": [[2,4]]
},
"possibleMoves":[
{
"board": {},
"possibleMoves": [{}]
}
]
},
{
"board": {
"starts": [[0,3]],
"blocks": [[3,0],[3,3]],
"ends": [[2,4]]
},
"possibleMoves":[{}]
}]
}
我可以弄清楚如何从顶层板上添加可能的移动,但我无法弄清楚如何循环遍历第二层中的所有结果板并找出它们可能的移动,并且然后循环遍历所有第三层板,依此类推。如何添加可能的移动并使用广度优先搜索遍历对象?
I am making a program that solves a puzzle game, and it finds all the possible moves on a board and puts all the possible resulting boards in an object. Then it finds all the possible moves for the resulting boards, and so on. The object will look something like this:
{
"board": {
"starts": [[0,0],[0,3]],
"blocks": [[3,0],[3,3]],
"ends": [[2,4]]
},
"possibleMoves": [
{
"board": {
"starts": [[0,0],[2,3]],
"blocks": [[3,0],[3,3]],
"ends": [[2,4]]
},
"possibleMoves":[
{
"board": {},
"possibleMoves": [{}]
}
]
},
{
"board": {
"starts": [[0,3]],
"blocks": [[3,0],[3,3]],
"ends": [[2,4]]
},
"possibleMoves":[{}]
}]
}
I can figure out how to add the possible moves from the top-level board, but I cannot figure out how to loop through all the resulting boards in the second level and figure out their possible moves, and then loop through all the third level boards and so on. How can I add the possible moves and traverse the object using a breadth-first search?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
递归。
编辑:对于广度优先搜索,请尝试这样的操作。它不使用递归,而是迭代不断增长的队列。
Recursion.
EDIT: For a breadth-first search, try something like this. It doesn't use recursion, but instead iterates over a growing queue.
未完全测试:
Not completely tested:
我没有 JavaScript 描述,但我通常会通过保留未探索节点的队列来实现。
另外还有一些伪pod维基百科页面以及更多解释
此处
Google 快速搜索还发现了类似的算法,可以满足您的目的
此处
I don't have a JavaScript description but i would generally do it by keeping a queue of unexplored nodes.
Also there is some pseudopod on the Wikipedia page as well as some more explanations
HERE
Also a quick Google search turned up a similar algorithm that could be bent to your purpose
HERE