题目主要来源:LeetCode。主要选自剑指offer、程序员面试宝典。
每日尽可能保持 N+1 道题,N 取 0 到 9。部分解法是从LeetCode上大佬们的解法中拿过来的,如有侵权,告知立删
/**
* JZ12 回溯
*
* @author Anjude
* @date 2021/7/4 17:34
*/
public class JZ12 {
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;
}
boolean dfs(char[][] board, char[] word, int i, int j, int k) {
// 越界或者字符不匹配 -- 此路不通
if (i >= board.length || i < 0 || j >= board[0].length || j < 0 || board[i][j] != word[k]) return false;
// 最后一个字符匹配,返回true
if (k == word.length - 1) return true;
board[i][j] = '\0';
boolean res = dfs(board, word, i + 1, j, k + 1) || dfs(board, word, i - 1, j, k + 1) ||
dfs(board, word, i, j + 1, k + 1) || dfs(board, word, i, j - 1, k + 1);
board[i][j] = word[k];
return res;
}
public static void main(String[] args) {
JZ12 jz12 = new JZ12();
jz12.exist(new char[][]{{'a','b'},{'a','b'}}, "abb");
}
}
/**
* JZ5 可以用replace,也可以用StringBuilder遍历
*
* @author Anjude
* @date 2021/7/4 22:05
*/
public class JZ5 {
public String replaceSpace(String s) {
StringBuilder sb = new StringBuilder();
for(char c : s.toCharArray()){
if(c == ' ') sb.append("%20");
else sb.append(c);
}
return sb.toString();
}
}
/**
* JZ13 dfs
*
* @author Anjude
* @date 2021/7/4 22:33
*/
public class JZ13 {
public int movingCount(int m, int n, int k) {
boolean[][] visited = new boolean[m][n];
return dfs(0, 0, m, n, k, visited);
}
private int dfs(int i, int j, int m, int n, int k, boolean[][] visited) {
// 终止条件:边界、不符合条件、已访问点
if (i < 0 || i >= m || j < 0 || j >= n || (i / 10 + i % 10 + j / 10 + j % 10) > k || visited[i][j]) {
return 0;
}
visited[i][j] = true;
return dfs(i + 1, j, m, n, k, visited) + dfs(i - 1, j, m, n, k, visited) +
dfs(i, j + 1, m, n, k, visited) + dfs(i, j - 1, m, n, k, visited) + 1;
}
}