710037. Find shortest safe route in a matrix
Medium
Here is a detailed Markdown blog post for the problem:
Find shortest safe route in a matrix
Slug: find-shortest-safe-route-in-a-matrix
Difficulty: Medium
Id: 710037
Topic Tags: DFS, Graph
Company Tags: None
Summary
Given a binary matrix, find the shortest path from the top left cell to the bottom right cell while avoiding cells with value 0. This problem involves graph traversal and dynamic programming concepts.
Detailed Explanation
The approach is based on Depth-First Search (DFS) algorithm. The DFS starts from the top-left cell and explores all neighboring cells that have a value of 1 until it reaches the bottom-right cell. We keep track of the minimum distance to reach each cell.
Here's a step-by-step breakdown:
- Initialize the distances array with infinite values for all cells.
- Start DFS from the top-left cell (0,0) and explore all neighboring cells that have a value of 1 in increasing order of their Manhattan distance.
- If we find the bottom-right cell (m-1,n-1), return the distance as it is the shortest safe route.
- If we encounter a cell with value 0 or exceed the boundaries of the matrix, backtrack and explore another path.
Here's an ASCII art diagram to illustrate this:
+-----+-----+
| | |
+-----+-----+
| 0 | 1 |
+-----+-----+
| | |
+-----+-----+
| 1 | 1 |
+-----+-----+
| | |
+-----+-----+
Time complexity: O(mn) where m is the number of rows and n is the number of columns in the matrix. Space complexity: O(mn) for storing distances.
Optimized Solutions
Java
public class Main {
public static void main(String[] args) {
int[][] grid = {
{0, 1, 1, 0},
{0, 1, 1, 0},
{0, 0, 1, 1}
};
System.out.println(shortestSafeRoute(grid));
}
public static int shortestSafeRoute(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
int[][] distances = new int[m][n];
for (int i = 0; i < m; i++) {
Arrays.fill(distances[i], Integer.MAX_VALUE);
}
dfs(grid, distances, 0, 0);
return distances[m-1][n-1];
}
public static void dfs(int[][] grid, int[][] distances, int i, int j) {
if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == 0) return;
if (distances[i][j] != Integer.MAX_VALUE) return;
distances[i][j] = 1 + Math.min(Math.min(dfs(grid, distances, i-1, j), dfs(grid, distances, i+1, j)), dfs(grid, distances, i, j-1));
}
}