Free 5-Day Mini-Course: [ Ссылка ]
Try Our Full Platform: [ Ссылка ]
📹 Intuitive Video Explanations
🏃 Run Code As You Learn
💾 Save Progress
❓New Unseen Questions
🔎 Get All Solutions
Question: Given a 2D array of black and white entries representing a maze with designated entrance and exit points, find a path from the entrance to the exit, if one exists.
Graph search methodologies apply well to problems that have an aspect of a spatial relationship.
Approach 1 (Brute Force)
We could try to enumerate all possible paths in the maze from the start to the finish and then check all paths to see if any of them are valid (have all white squares, aka do not run over a wall).
This is both naive and extremely costly in terms of time.
Approach 2 (Graph BFS or DFS)
We will imagine each cell as a vertex and each adjacent relationship as the edges connecting nodes.
Do we use DFS or BFS?
If we use BFS we know that the path that we find will be the shortest path because of how it searches (wide, going out layer by layer).
If we use DFS we can have the call stack remember the path making things easier to implement.
If we hit the end cell, then we will know that every call below in the call stack has a node apart of the answer path.
Since the problem just wants any path then we will use DFS since it is more straight-forward.
Complexities
Time: O( | V | + | E | )
The standard time complexity for DFS
Space: O( | V | )
We will at maximum the length of the path on the call stack through our recursion
Note: The problem on Leetcode requires BFS to pass because DFS will not always find the shortest path, but I did DFS in this video just for teaching purposes.
++++++++++++++++++++++++++++++++++++++++++++++++++
HackerRank: [ Ссылка ]
Tuschar Roy: [ Ссылка ]
GeeksForGeeks: [ Ссылка ]
Jarvis Johnson: [ Ссылка ]
Success In Tech: [ Ссылка ]
++++++++++++++++++++++++++++++++++++++++++++++++++
This question is number 19.1 in "Elements of Programming Interviews" by Adnan Aziz, Tsung-Hsien Lee, and Amit Prakash.
Ещё видео!