【发布时间】:2015-08-08 23:23:59
【问题描述】:
最近我一直被困在“探索网格”的算法上。我想根据可能位于网格上任何位置的起始正方形绘制在网格的某个部分内有效的所有移动。我最初的计划是在 4 个方向上使用递归拆分标记网格,直到它达到边界或移动限制。探索的“分支”不能沿对角线移动:
*注意:箭头不代表堆栈中的出现,它们用于可视化算法的概念
private void Explore(byte moves, byte row, char col) {
if (row >= Grid[0].Count || col >= Grid.Count || row + col + 2 > moves) {//var < 0 handled b/c byte b = 0; (byte)(b-1) == 255
return;
}
Grid[row][col].color = ...;//mark it
if (Grid[row + 1][col + 1] == notVisited) Explore((byte) (moves - 1), (byte)(row + 1), (char) (col + 1));
if (Grid[row - 1][col + 1]== notVisited) Explore((byte)(moves - 1), (byte)(row - 1), (char) (col + 1));
if (Grid[row - 1][col - 1] == notVisited) Explore((byte)(moves - 1), (byte)(row - 1), (char) (col - 1));
if (Grid[row + 1][col - 1] == notVisited) Explore((byte)(moves - 1), (byte)(row + 1), (char) (col - 1));
}
我知道这个算法不起作用 b/c 我做了一个快速可运行示例here,其中算法卡在值之间,直到它触发运行时错误。
所以在这一点上:
递归还有可能吗(切换到迭代)?
有没有更好的替代算法来解决这个问题?
我的算法是否接近,但需要一些调整?
【问题讨论】:
-
您熟悉 A-star 或 Dijkstra 的最短路径算法吗?
-
如果你可以在每个点的所有 4 个方向上移动,你会得到很多循环(例如 left->right->left->right-> ...)所以有无限多的路径- 所以第一件事是你将删除循环。接下来是你确实应该只对最短路径感兴趣(是的,A* 就是这样)
-
@PieterGeerkens 我希望“遍历”所有可能的路径,而不仅仅是最好的。