712184. Grid Path 2
Grid Path 2
Slug: grid-path-2
Difficulty: Medium
Id: 712184
Topic Tags: Matrix, Dynamic Programming, Arrays, Data Structures, Algorithms
Summary
The problem "Grid Path 2" involves finding the shortest path in a grid that starts at a given cell and ends at another specified cell. The problem can be solved using dynamic programming concepts.
Detailed Explanation
Given a grid of size m x n, where each cell contains a value, we need to find the shortest path from a starting point (x1, y1) to an ending point (x2, y2). The cells are connected if they share an edge (i.e., either horizontally or vertically). Each step can only be taken in one of four directions: up, down, left, or right.
To solve this problem, we can use dynamic programming. We will create a 2D array dp of size (m+1) x (n+1) to store the minimum distance from each cell to the starting point. The base case is when the current cell is the starting point, in which case the minimum distance is 0.
For each cell, we consider all possible moves: up, down, left, or right. If a move is valid (i.e., it does not go out of bounds), and the new cell has not been visited before, we update the dp array with the minimum distance plus the value of the current cell.
The final answer will be stored in the cell corresponding to the ending point (x2, y2).
Here is a step-by-step breakdown of the solution:
1. Initialize dp array with infinity for all cells.
2. Set dp[x1][y1] = 0 as it's the starting point.
3. For each cell (i, j) in the grid:
- If the current cell is out of bounds or has been visited before, skip to the next cell.
- Consider all possible moves: up, down, left, or right.
- For each move:
- Check if the new cell is within bounds and hasn't been visited before.
- If it's a valid move, update dp[i][j] with the minimum distance plus the value of the current cell.
4. The final answer will be stored in dp[x2][y2].
Time complexity: O(m * n) Space complexity: O(m * n)
Optimized Solutions
Java
public class GridPath {
public static int minPath(int[][] grid, int x1, int y1, int x2, int y2) {
int m = grid.length;
int n = grid[0].length;
int[][] dp = new int[m+1][n+1];
for (int i = 0; i <= m; i++) {
for (int j = 0; j <= n; j++) {
dp[i][j] = Integer.MAX_VALUE;
}
}
dp[x1][y1] = 0;
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (i == x1 && j == y1) continue;
int minDist = Integer.MAX_VALUE;
if (i > 0 && dp[i-1][j] + grid[i-1][j] < minDist) minDist = dp[i-1][j] + grid[i-1][j];
if (i < m && dp[i+1][j] + grid[i+1][j] < minDist) minDist = dp[i+1][j] + grid[i+1][j];
if (j > 0 && dp[i][j-1] + grid[i][j-1] < minDist) minDist = dp[i][j-1] + grid[i][j-1];
if (j < n && dp[i][j+1] + grid[i][j+1] < minDist) minDist = dp[i][j+1] + grid[i][j+1];
dp[i][j] = minDist;
}
}
return dp[x2][y2];
}
}