【问题标题】:Grid exploring algorithm with move constraints具有移动约束的网格探索算法
【发布时间】: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,其中算法卡在值之间,直到它触发运行时错误。

所以在这一点上:

  1. 递归还有可能吗(切换到迭代)?

  2. 有没有更好的替代算法来解决这个问题?

  3. 我的算法是否接近,但需要一些调整?

【问题讨论】:

  • 您熟悉 A-star 或 Dijkstra 的最短路径算法吗?
  • 如果你可以在每个点的所有 4 个方向上移动,你会得到很多循环(例如 left->right->left->right-> ...)所以有无限多的路径- 所以第一件事是你将删除循环。接下来是你确实应该只对最短路径感兴趣(是的,A* 就是这样)
  • @PieterGeerkens 我希望“遍历”所有可能的路径,而不仅仅是最好的。

标签: c# algorithm recursion


【解决方案1】:

搜索的想法应该可以正常工作,但代码不起作用的原因是因为它正在检查对角线。

if (Grid[row + 1][col + 1] == notVisited)
if (Grid[row - 1][col + 1]== notVisited) 
if (Grid[row - 1][col - 1] == notVisited) 
if (Grid[row + 1][col - 1] == notVisited)

我想你的意思是:

if (Grid[row + 1][col] == notVisited)
if (Grid[row - 1][col]== notVisited) 
if (Grid[row][col + 1] == notVisited) 
if (Grid[row][col - 1] == notVisited)

问题:

1:递归很好。迭代会更快,但不会产生太大影响。

2:可能有很多不同的方法可以做到这一点,但目前的方法应该没问题。

3:除了改变这四个条件之外,这个条件

|| row + col + 2 > moves)

可能会导致程序根据放置位置而出现奇怪的行为。 moves 参数对于所有递归路径都不相同,因此大多数时候程序可能会绘制整个网格。除此之外,程序应该可以正常运行。

【讨论】:

    【解决方案2】:

    您似乎希望实现depth-first search。 wiki 文章甚至提供了一些伪代码,您可以使用它们来实现算法。

    请注意,这将标记所有可到达的方格,但不会打印出所有(冗余)移动,除非您修改算法。

    【讨论】:

    猜你喜欢
    • 2015-04-22
    • 1970-01-01
    • 2017-03-22
    • 2015-06-30
    • 1970-01-01
    • 2017-01-01
    • 2015-07-18
    • 1970-01-01
    • 2015-02-09
    相关资源
    最近更新 更多