Course launching November 17, 2020
Follow me on YouTube for free coding interview videos.
Users who sign up for the email list will receive an exclusive 75% discount at launch.
You're training a robot to walk through a room and search for an exit. The room will be represented as a matrix. For simplicity, the robot will always start at the top-left and can only walk down or right.
There may or may not be a path to the exit in the room.
An open node is represented by
0, a blocked node is represented by
1, and an exit is represented by
Write a function
hasExitPath that returns a boolean if there is path to an exit or not.
hasExitPath([ [0, 0, 0], [0, 0, 1], [0, 0, 1], [1, 0, 2], ]); // true hasExitPath([ [0, 0, 0, 0], [1, 0, 0, 1], [2, 1, 0, 0], ]); // false
Validate My Answer
There can be many paths. We only care if there is at least one, and then we can return true.
If you solve this recursively, you may be doing a lot of repeated operations. Try to remove these duplicate operations to improve your time complexity.
You can solve this in O(r x c) time and space, where
ris the number of rows and
cis the number of columns.