leetcode-1391-Check if There is a Valid Path in a Grid
问题
Given a m x n grid
. Each cell of the grid
represents a street. The street of grid[i][j]
can be:
- 1 which means a street connecting the left cell and the right cell.
- 2 which means a street connecting the upper cell and the lower cell.
- 3 which means a street connecting the left cell and the lower cell.
- 4 which means a street connecting the right cell and the lower cell.
- 5 which means a street connecting the left cell and the upper cell.
- 6 which means a street connecting the right cell and the upper cell.
You will initially start at the street of the upper-left cell (0,0)
. A valid path in the grid is a path which 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.
Notice that you are not allowed to change any street.
Return true if there is a valid path in the grid or false otherwise.
Example 1:
1 | Input: grid = [[2,4,3],[6,5,2]] |
Example 2:
1 | Input: grid = [[1,2,1],[1,2,1]] |
Example 3:
1 | Input: grid = [[1,1,2]] |
Example 4:
1 | Input: grid = [[1,1,1,1,1,1,3]] |
Example 5:
1 | Input: grid = [[2],[2],[2],[2],[2],[2],[6]] |
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 300
1 <= grid[i][j] <= 6
分析
使用深度优先搜索,或者广度优先搜索,从坐标 (0, 0) 开始判断是否可达 (m-1, n-1)。这个问题的麻烦点在于,如何判断当前位置是否可以和下一个位置之间联通,单向连通还不行,一定要双向联通。个人的思路是,判断一个位置可以接收到来自哪个方向的输入,比如 street 3,它的上一条的地址可以来自于它的下方和左方。想这样来增加判断条件。rexue70 的方法是,当前位置能够进入到下一个位置,并且下一个位置也能回到当前位置时,才能将下一个的位置判定为有效。
代码1
1 | // DFS |
代码2
1 | class Solution { |
Author: Hatton.Liu
Link: http://hattonl.github.io/2020/03/22/leetcode-1391/
License: 知识共享署名-非商业性使用 4.0 国际许可协议