阅读设置
界面、侧栏和正文分别调整,自动保存。
主题切换
界面、侧栏和正文分别调整,自动保存。
问题描述:
给你一个 m x n 的网格 grid,每个单元格代表一条特定类型的街道,街道类型定义如下:
你从左上角 (0,0) 出发,目标是到达右下角 (m-1, n-1),路径必须严格沿着街道的连接方向前进,且不能修改街道类型。如果存在这样的有效路径,返回 true,否则返回 false。
示例:
输入:
grid = [[2,4,3],[6,5,2]]输出:true解释:存在一条从(0,0)到(1,2)的有效路径。
输入:
grid = [[1,1,1,1,1,1,3]]输出:true解释:沿着水平街道一直向右,最终到达终点。
(0,0) 开始,标记已访问单元格;true。true,否则返回 false。package lc1391;
class lc1391.Solution {
int[] dirX = {-1, 1, 0, 0};
int[] dirY = {0, 0, -1, 1};
int[] reverseDir = {1, 0, 3, 2};
int[][] streets = {{}, {2, 3}, {0, 1}, {2, 1}, {3, 1}, {2, 0}, {3, 0}};
public boolean hasValidPath(int[][] grid) {
int n = grid.length;
int m = grid[0].length;
boolean[][] visited = new boolean[n][m];
return dfs(grid, 0, 0, visited);
}
private boolean dfs(int[][] grid, int x, int y, boolean[][] visited) {
int n = grid.length;
int m = grid[0].length;
visited[x][y] = true;
if (x == n - 1 && y == m - 1) {
return true;
}
int type = grid[x][y];
for (int dir : streets[type]) {
int nx = x + dirX[dir];
int ny = y + dirY[dir];
if (nx >= 0 && nx < n && ny >= 0 && ny < m && !visited[nx][ny]) {
int reverse = reverseDir[dir];
int nextType = grid[nx][ny];
for (int nd : streets[nextType]) {
if (nd == reverse) {
if (dfs(grid, nx, ny, visited)) {
return true;
}
break;
}
}
}
}
return false;
}
}当网格较大时,DFS 递归可能导致栈溢出,可改用 BFS 实现:
public boolean hasValidPath(int[][] grid) {
int n = grid.length;
int m = grid[0].length;
boolean[][] visited = new boolean[n][m];
Queue<int[]> queue = new LinkedList<>();
queue.add(new int[]{0, 0});
visited[0][0] = true;
while (!queue.isEmpty()) {
int[] curr = queue.poll();
int x = curr[0], y = curr[1];
if (x == n - 1 && y == m - 1) return true;
int type = grid[x][y];
for (int dir : streets[type]) {
int nx = x + dirX[dir];
int ny = y + dirY[dir];
if (nx >= 0 && nx < n && ny >= 0 && ny < m && !visited[nx][ny]) {
int reverse = reverseDir[dir];
int nextType = grid[nx][ny];
for (int nd : streets[nextType]) {
if (nd == reverse) {
visited[nx][ny] = true;
queue.add(new int[]{nx, ny});
break;
}
}
}
}
}
return false;
}在遍历过程中,一旦到达终点 (m-1, n-1),立即返回 true,无需继续遍历。
将街道类型、方向、反向方向全部预定义为数组,避免重复判断,提升代码可读性与执行效率。
时间复杂度:
空间复杂度:
visited 占用