如何解决迷宫拼图中的多项式时间大鼠?

时间:2016-08-07 15:20:01

标签: algorithm time-complexity path-finding

我最近在面试中被问到this question

  

迷宫是作为源块所在的块的N * N二进制矩阵给出的   最左上方的块,即迷宫[0] [0]和目标块是   最右下方的块,即迷宫[N-1] [N-1]。老鼠从源头开始   并且必须到达目的地。老鼠只能朝两个方向移动:   向前和向下。 (或4个高级问题)。在迷宫矩阵中,0   块表示块是死角,1表示块可以用于   从源头到目的地的路径。

我的回答是链接中提到的那个,它使用了回溯。来自链接的高级伪代码:

If destination is reached
    print the solution matrix
Else
   a) Mark current cell in solution matrix as 1. 
   b) Move forward in horizontal direction and recursively check if this 
       move leads to a solution. 
   c) If the move chosen in the above step doesn't lead to a solution
       then move down and check if  this move leads to a solution. 
   d) If none of the above solutions work then unmark this cell as 0 
       (BACKTRACK) and return false.

面试官对我的回答感到非常惊讶,显然期待多项式时间解决方案。

这个问题是否存在多项式时间解决方案?

1 个答案:

答案 0 :(得分:0)

这可以使用BFS以线性时间解决。

问题实际上是一个图形,其中所有单元格都是顶点,并且可能从单元格移动是边缘。您正在寻找从某个源到目的地的最短路径,这正是BFS所做的。

(请注意,在仅允许“向下”和“向右”的简化问题中,有效路径具有相同的长度。虽然对于具有4个允许方向的更复杂问题,但情况并非如此)

要生成实际路径,您需要通过“记住”探索的每个节点的父节点来跟踪路径。这在问题中讨论:How can I find the actual path found by BFS?

相关问题