-4

I was recently asked this question in an Interview:

A Maze is given as N*N binary matrix of blocks where source block is the upper left most block i.e., maze[0][0] and destination block is lower rightmost block i.e., maze[N-1][N-1]. A rat starts from source and has to reach destination. The rat can move only in two directions: forward and down. (or 4 in advanced problem). In the maze matrix, 0 means the block is dead end and 1 means the block can be used in the path from source to destination.

My answer was the one mentioned in the link, which is using backtracking. High level pseudo code from the link:

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.

The interviewer was quite surprised by my response , and was apparently expecting a polynomial time solution.

Does there exist a polynomial time solution for this problem?

amit
  • 175,853
  • 27
  • 231
  • 333
Neeraj
  • 137
  • 1
  • 2
  • 9
  • 1
    Take the time to include all the necessary details in your post here and avoid relying on external sites. See the [How to Ask](http://stackoverflow.com/help/how-to-ask) page. – code_dredd Aug 07 '16 at 15:22
  • @amit thanks for taking the time out to edit my question and give an answer.@ray I would definitely take care to follow your advice and How to Ask guidelines in my future posts. – Neeraj Aug 08 '16 at 08:57

1 Answers1

1

This can be solved in linear time using BFS.

The problem is actually a graph, where all cells are vertices and a possible move from cells is the edges. You are looking for the shortest path from some source to the destination, which is exactly what BFS does.

(Note that in simplified problem with only "down" and "right" allowed, valid path has the same length. This is not true though for the more complex problem with 4 allowed directions)

To generate the actual path, you need to keep track of the path by "remembering" the parent of each node explored. This is discussed in the question: How can I find the actual path found by BFS?

Community
  • 1
  • 1
amit
  • 175,853
  • 27
  • 231
  • 333