题目描述:
给你一个 m x n 的网格 grid。网格里的每个单元都代表一条街道。grid[i][j] 的街道可以是:
1 表示连接左单元格和右单元格的街道。
2 表示连接上单元格和下单元格的街道。
3 表示连接左单元格和下单元格的街道。
4 表示连接右单元格和下单元格的街道。
5 表示连接左单元格和上单元格的街道。
6 表示连接右单元格和上单元格的街道。
你最开始从左上角的单元格 (0,0) 开始出发,网格中的「有效路径」是指从左上方的单元格 (0,0) 开始、一直到右下方的 (m-1,n-1) 结束的路径。该路径必须只沿着街道走。
注意:你 不能 变更街道。
如果网格中存在有效的路径,则返回 true,否则返回 false 。
示例 1:
输入:grid = [[2,4,3],[6,5,2]]
输出:true
解释:如图所示,你可以从 (0, 0) 开始,访问网格中的所有单元格并到达 (m - 1, n - 1) 。
示例 2:
输入:grid = [[1,2,1],[1,2,1]]
输出:false
解释:如图所示,单元格 (0, 0) 上的街道没有与任何其他单元格上的街道相连,你只会停在 (0, 0) 处。
示例 3:
输入:grid = [[1,1,2]]
输出:false
解释:你会停在 (0, 1),而且无法到达 (0, 2) 。
示例 4:
输入:grid = [[1,1,1,1,1,1,3]]
输出:true
示例 5:
输入:grid = [[2],[2],[2],[2],[2],[2],[6]]
输出:true
提示:
m == grid.length
n == grid[i].length
1 <= m, n <= 300
1 <= grid[i][j] <= 6
方法1:
主要思路:解题链接汇总
(1)直接模拟题意;
(2)处理第一个位置是第四种街道的特殊类型;
class Solution {
public:
bool helper(vector<vector<int>>&grid,vector<vector<bool>>&signs,int cur_row,int cur_col){
int m=grid.size(),n=grid[0].size();
vector<vector<int>> next={{0,1},{0,-1},{1,0},{-1,0}};
vector<vector<int>> neighbor={{1,3,5},{1,4,6},{2,5,6},{2,3,4}};
vector<vector<int>> path={{},{0,1},{2,3},{1,2},{0,2},{1,3},{0,3}};
while(true){
if(cur_row==m-1&&cur_col==n-1){
return true;
}
signs[cur_row][cur_col]=true;
int tmp_row=cur_row+next[path[grid[cur_row][cur_col]][0]][0];
int tmp_col=cur_col+next[path[grid[cur_row][cur_col]][0]][1];
int index=path[grid[cur_row][cur_col]][0];
if(tmp_row<0||tmp_row>=m||tmp_col<0||tmp_col>=n||signs[tmp_row][tmp_col]){
tmp_row=cur_row+next[path[grid[cur_row][cur_col]][1]][0];
tmp_col=cur_col+next[path[grid[cur_row][cur_col]][1]][1];
index=path[grid[cur_row][cur_col]][1];
}
if(tmp_row<0||tmp_row>=m||tmp_col<0||tmp_col>=n||signs[tmp_row][tmp_col]){
return false;
}
int i=0;
for(i=0;i<3;++i){
if(neighbor[index][i]==grid[tmp_row][tmp_col]){
cur_row=tmp_row;
cur_col=tmp_col;
break;
}
}
if(i==3){
return false;
}
}
return false;
}
bool hasValidPath(vector<vector<int>>& grid) {
int cur_row=0,cur_col=0;
vector<vector<bool>> signs(grid.size(),vector<bool>(grid[0].size(),false));
if(grid[cur_row][cur_col]!=4){
return helper(grid,signs,cur_row,cur_col);
}
signs[0][0]=true;
return helper(grid,signs,0,1)||helper(grid,signs,1,0);
}
};