Path Finder in a Binary Maze
Given a binary matrix where 0 represents an obstacle and 1 represents an open path, write a function to determine if there exists any route from the top-left corner to the bottom-right corner. The function should return true if such a path exists and false otherwise. You can move up, down, left, or right, but not diagonally.
[ [ 1, 0, 0, 0 ], [ 1, 1, 0, 1 ], [ 0, 1, 0, 0 ], [ 1, 1, 1, 1 ] ]
Explanation. There is a path from the top left corner (0,0) to the bottom right corner (3,3) following the path (0,0) -> (1,0) -> (1,1) -> (1,3) -> (2,1) -> (3,1) -> (3,2) -> (3,3).
[ [ 1, 0, 0 ], [ 0, 0, 1 ], [ 1, 1, 0 ] ]
Explanation. There is no path from the top-left to the bottom-right corner because of complete obstructions formed by 0's.
[ [ 1, 1, 1 ], [ 1, 1, 1 ], [ 1, 1, 1 ] ]
Explanation. As there are no obstructions (0's), there is a straightforward path from (0,0) to (2,2) with all cells being accessible.
Follow-up: Can you solve the problem using both DFS and BFS approaches? Discuss the time complexities for each approach. Is there any optimization that can be applied if certain patterns are detected in the matrix?
1. The matrix is non-empty and is a rectangle.\n2. The values in the matrix are only 0's or 1's.
- Views
- 2