1.题目

2.思路(深度优先遍历DFS)
class Solution {
int[][] grid;
int m;
int n;
boolean[][] used;
int[][][] direction = {
{{0, -1, 1}, {0, -1, 4}, {0, -1, 6}, {0, 1, 1}, {0, 1, 3}, {0, 1, 5}},
{{-1, 0, 2}, {-1, 0, 3}, {-1, 0, 4}, {1, 0, 2}, {1, 0, 5}, {1, 0, 6}},
{{0, -1, 1}, {0, -1, 4}, {0, -1, 6}, {1, 0, 2}, {1, 0, 5}, {1, 0, 6}},
{{1, 0, 2}, {1, 0, 5}, {1, 0, 6}, {0, 1, 1}, {0, 1, 3}, {0, 1, 5}},
{{0, -1, 1}, {0, -1, 4}, {0, -1, 6}, {-1, 0, 2}, {-1, 0, 3}, {-1, 0, 4}},
{{0, 1, 1}, {0, 1, 3}, {0, 1, 5}, {-1, 0, 2}, {-1, 0, 3}, {-1, 0, 4}},
};
public boolean hasValidPath(int[][] grid){
this.grid = grid;
this.m = grid.length;
this.n = grid[0].length;
this.used = new boolean[m][n];
return judgeValidPath(0, 0);
}
public boolean judgeValidPath(int x, int y){
used[x][y] = true;
if(x == m-1 && y == n-1){
return true;
}
for(int[] p : direction[grid[x][y] - 1]){
int newX = x + p[0];
int newY = y + p[1];
if (isValid(newX, newY, p[2]) && judgeValidPath(newX, newY)) {
return true;
}
}
return false;
}
public boolean isValid(int x, int y, int type){
return x >= 0 && x < m && y >= 0 && y < n && !used[x][y] && grid[x][y] == type;
}
}