剑指 Offer 12. 矩阵中的路径
class Solution {
int m,n;
char[] c;
boolean[][] visited;
char[][] board;
int[][] directions=new int[][]{{0,1},{0,-1},{1,0},{-1,0}};
public boolean exist(char[][] board, String word) {
this.board=board;
m=board.length;
n=board[0].length;
c=word.toCharArray();
visited=new boolean[m][n];
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(board[i][j]==c[0]){
visited[i][j]=true;
if(backtrack(i,j,1)) return true;
visited[i][j]=false;;
}
}
}
return false;
}
private boolean backtrack(int i,int j,int next){
if(next==c.length) return true;
for(int[] dir:directions){
int x=i+dir[0];
int y=j+dir[1];
if(x>=0&&y>=0&&x<m&&y<n&&c[next]==board[x][y]&&!visited[x][y]){
visited[x][y]=true;
if(backtrack(x, y, next+1)) return true;
visited[x][y]=false;
}
}
return false;
}
}
剑指 Offer 13. 机器人的运动范围
class Solution {
boolean[][] reachable;
boolean[][] checked;
int m,n,k;
public int movingCount(int m, int n, int k) {
this.m=m;
this.n=n;
this.k=k;
reachable =new boolean[m][n];
checked=new boolean[m][n];
dfs(0,0);
int count=0;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(reachable[i][j]) count++;
}
}
return count;
}
private void dfs(int i,int j){
if(i<0||j<0||i>=m||j>=n||checked[i][j]){
return;
}
checked[i][j]=true;
if(calculate(i, j)<=k){
reachable[i][j]=true;
dfs(i+1,j);
dfs(i-1,j);
dfs(i,j+1);
dfs(i,j-1);
}else{
reachable[i][j]=false;
}
}
private int calculate(int i,int j){
int count=0;
while(i>0){
count+=i%10;
i=i/10;
}
while(j>0){
count+=j%10;
j=j/10;
}
return count;
}
}
329. 矩阵中的最长递增路径
说是记忆化dfs
class Solution {
public int longestIncreasingPath(int[][] matrix) {
int m = matrix.length;
if (m == 0) return 0;
int n = matrix[0].length;
int[][] note = new int[m][n];
int max = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (note[i][j] == 0) {
dfs(i, j, matrix, note);
}
max = Math.max(max, note[i][j]);
}
}
return max;
}
public int dfs(int i, int j, int[][] matrix, int[][] note) {
if (note[i][j] != 0) {
return note[i][j];
}
note[i][j]++;
int[][] directions = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
for (int[] dir : directions) {
int x = i + dir[0];
int y = j + dir[1];
if (x >= 0 && y >= 0 && x < matrix.length && y < matrix[0].length && matrix[x][y] > matrix[i][j]) {
note[i][j] = Math.max(note[i][j], dfs(x, y, matrix, note) + 1);
}
}
return note[i][j];
}
}