力扣
剑指Offer 13
DBS解法
1.函数sums用来计算数位之和
class Solution {
int m, n, k;
boolean[][] visited;
public int movingCount(int m, int n, int k) {
this.m = m; this.n = n; this.k = k;
this.visited = new boolean[m][n]; //标记数组,机器人是否到过
return dfs(0, 0, k);
}
public int dfs(int i,int j,int k){
if(i>=m||j>=n||sums(i)+sums(j)>k||visited[i][j]) //判断机器人是否出界,和是否到过
return 0;
visited[i][j]=true; //标记该点来过
return 1 + dfs(i+1,j,k)+dfs(i,j+1,k); //因为机器人从(0,0)出发,所以只用往右和下遍历
}
public int sums(int x){
int s = 0;
while(x != 0) {
s += x % 10;
x = x / 10;
}
return s;
}
}
剑指Offer 12
DBS解法
class Solution {
public boolean exist(char[][] board, String word) {
char[] words = word.toCharArray();
for(int i = 0; i < board.length; i++) {
for(int j = 0; j < board[0].length; j++) {
if(dfs(board,words,i,j,0)) return true;
}
}
return false;
}
//words数组是需要查找的单词,k是目前已经找到的第几位
public boolean dfs(char[][] board, char[] words,int i,int j,int k){
//判断边界条件,是否满足题意
if(i<0||i>=board.length||j<0||j>=board[0].length||board[i][j]!=words[k])
return false;
//此时已经找完,直接返回true
if(k==words.length-1)
return true;
//将board[i][j]变为'\0' 可以节省标记数组的空间
board[i][j] = '\0';
//进行上下左右遍历
boolean res = dfs(board, words, i + 1, j, k + 1) ||
dfs(board, words, i - 1, j, k + 1) ||
dfs(board, words, i, j + 1, k + 1) ||
dfs(board, words, i , j - 1, k + 1);
board[i][j] = words[k];
return res;
}
}