Leetcode 1391: Check if There is a Valid Path in a Grid

grid47
grid47
Exploring patterns and algorithms
Jun 20, 2024 8 min read

You are given an m x n grid where each cell represents a street. The streets have different connections between neighboring cells. Starting from the top-left corner of the grid, you need to find if there exists a valid path to the bottom-right corner, following the direction of the streets.
Problem
Approach
Steps
Complexity
Input: You are given an m x n grid where grid[i][j] is an integer between 1 and 6 that represents the type of street connecting cells.
Example: For grid = [[1,2,3],[6,5,4]], the output is true.
Constraints:
• 1 <= m, n <= 300
• 1 <= grid[i][j] <= 6
Output: Return true if there is a valid path from the top-left corner to the bottom-right corner, otherwise return false.
Example: For grid = [[1,2,3],[6,5,4]], the output is true.
Constraints:
• Return false if no valid path exists.
Goal: The goal is to check if there is a valid path from the top-left to the bottom-right corner of the grid by moving only through the valid streets.
Steps:
• 1. Initialize a queue to perform BFS starting from (0, 0).
• 2. For each cell, check its possible directions based on the street type.
• 3. If a direction leads to an unvisited cell and the connection is valid, add it to the queue.
• 4. Continue until the queue is empty or the bottom-right corner is reached.
• 5. If you reach (m-1, n-1), return true. If not, return false.
Goal: The algorithm should efficiently handle grids with a size up to 300x300.
Steps:
• Ensure the BFS search avoids revisiting cells.
Assumptions:
• You can assume that the input grid will always be valid.
Input: For grid = [[1,2,3],[6,5,4]], starting from (0, 0) leads to (1, 2), which connects to (1, 1), and from there, you can reach the bottom-right corner.
Explanation: Each cell has specific street types that define its possible connections. By carefully following these, you can determine if a path exists.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus