1391. Check if There is a Valid Path in a Grid Medium

@problem@discussion
#Array#Depth-First Search#Breadth-First Search#Union Find#Matrix



1/**
2 * [1391] Check if There is a Valid Path in a Grid
3 *
4 * You are given an m x n grid. Each cell of grid represents a street. The street of grid[i][j] can be:
5 * 
6 * 	1 which means a street connecting the left cell and the right cell.
7 * 	2 which means a street connecting the upper cell and the lower cell.
8 * 	3 which means a street connecting the left cell and the lower cell.
9 * 	4 which means a street connecting the right cell and the lower cell.
10 * 	5 which means a street connecting the left cell and the upper cell.
11 * 	6 which means a street connecting the right cell and the upper cell.
12 * <img alt="" src="https://assets.leetcode.com/uploads/2020/03/05/main.png" style="width: 450px; height: 708px;" />
13 * You will initially start at the street of the upper-left cell (0, 0). A valid path in the grid is a path that starts from the upper left cell (0, 0) and ends at the bottom-right cell (m - 1, n - 1). The path should only follow the streets.
14 * Notice that you are not allowed to change any street.
15 * Return true if there is a valid path in the grid or false otherwise.
16 *  
17 * Example 1:
18 * <img alt="" src="https://assets.leetcode.com/uploads/2020/03/05/e1.png" style="width: 455px; height: 311px;" />
19 * Input: grid = [[2,4,3],[6,5,2]]
20 * Output: true
21 * Explanation: As shown you can start at cell (0, 0) and visit all the cells of the grid to reach (m - 1, n - 1).
22 * 
23 * Example 2:
24 * <img alt="" src="https://assets.leetcode.com/uploads/2020/03/05/e2.png" style="width: 455px; height: 293px;" />
25 * Input: grid = [[1,2,1],[1,2,1]]
26 * Output: false
27 * Explanation: As shown you the street at cell (0, 0) is not connected with any street of any other cell and you will get stuck at cell (0, 0)
28 * 
29 * Example 3:
30 * 
31 * Input: grid = [[1,1,2]]
32 * Output: false
33 * Explanation: You will get stuck at cell (0, 1) and you cannot reach cell (0, 2).
34 * 
35 *  
36 * Constraints:
37 * 
38 * 	m == grid.length
39 * 	n == grid[i].length
40 * 	1 <= m, n <= 300
41 * 	1 <= grid[i][j] <= 6
42 * 
43 */
44pub struct Solution {}
45
46// problem: https://leetcode.com/problems/check-if-there-is-a-valid-path-in-a-grid/
47// discuss: https://leetcode.com/problems/check-if-there-is-a-valid-path-in-a-grid/discuss/?currentPage=1&orderBy=most_votes&query=
48
49// submission codes start here
50
51impl Solution {
52    pub fn has_valid_path(grid: Vec<Vec<i32>>) -> bool {
53        false
54    }
55}
56
57// submission codes end
58
59#[cfg(test)]
60mod tests {
61    use super::*;
62
63    #[test]
64    fn test_1391() {
65    }
66}
67


Back
© 2025 bowen.ge All Rights Reserved.