[LeetCode][1091. Shortest Path in Binary Matrix] Why Use BFS? Search Every Possible Path vs Search A Possible Path
By Long Luo
This article is the solution Why Use BFS? Search Every Possible Path vs Search A Possible Path of Problem 1091. Shortest Path in Binary Matrix .
Intuition
If we want to find a possible path, DFS will be more efficient. Because DFS will return a possible path if found, while it may not the shortest path.
BFS will try every possible path at the same time.
If we want to find the shortest of all possible paths, BFS is more efficient. It’s impossible for DFS to determine which is the shortest before trying all possible paths.
BFS
Use BFS to Level Traversal.
1 | public int shortestPathBinaryMatrix(int[][] grid) { |
Analysis
- Time Complexity: \(O(n)\).
- Space Complexity: \(O(n)\).
All suggestions are welcome. If you have any query or suggestion please comment below. Please upvote👍 if you like💗 it. Thank you:-)
Explore More Leetcode Solutions. 😉😃💗