m == grid.length n == grid[i].length 1 <= m, n <= 300 1 <= grid[i][j] <= 6
解法
将这六种街道转换成 3 * 3 的方格,就变成了普通的迷宫问题,深搜广搜都行。
funchasValidPath(grid [][]int)bool { m, n := len(grid)*3, len(grid[0])*3 newGrid := make([][]bool, m) for i := range newGrid { newGrid[i] = make([]bool, n) } for i := range grid { // i 行 j 列 for j := range grid[i] { x, y := 3*j, 3*i // y 行 x 列 newGrid[y+1][x+1] = true switch grid[i][j] { case1: newGrid[y+1][x] = true newGrid[y+1][x+2] = true case2: newGrid[y][x+1] = true newGrid[y+2][x+1] = true case3: newGrid[y+1][x] = true newGrid[y+2][x+1] = true case4: newGrid[y+1][x+2] = true newGrid[y+2][x+1] = true case5: newGrid[y+1][x] = true newGrid[y][x+1] = true case6: newGrid[y][x+1] = true newGrid[y+1][x+2] = true } } } return dfs(1, 1, m, n, newGrid) // 注意起点 }
funcdfs(i, j, m, n int, grid [][]bool)bool { if i == m-1 && j == n-2 { // 终点 returntrue } if i < 0 || i >= m || j < 0 || j >= n || !grid[i][j] { returnfalse } grid[i][j] = false return dfs(i-1, j, m, n, grid) || dfs(i, j-1, m, n, grid) || dfs(i+1, j, m, n, grid) || dfs(i, j+1, m, n, grid) }