public class Solution {
public int movingCount(int threshold, int rows, int cols)
{
if(rows <= 0 || cols <= 0 || threshold < 0) return 0;
boolean[] visited = new boolean[rows * cols];
return dfs(threshold,rows,cols,visited,0,0);
}
private int dfs(int threshold, int rows, int cols, boolean[] visited, int x, int y) {
if(x < 0 || x >= cols || y < 0 || y >= rows
|| getDigitSum(x) + getDigitSum(y) > threshold || visited[x + y * cols])
return 0;//出口
visited[x + y * cols] = true;//标记
return 1 + dfs(threshold, rows, cols, visited, x, y - 1)//归
+ dfs(threshold, rows, cols, visited, x + 1, y)
+ dfs(threshold, rows, cols, visited, x, y + 1)
+ dfs(threshold, rows, cols, visited, x - 1, y);
}
private int getDigitSum(int i) {
int sum = 0;
while(i > 0) {
sum += i % 10;
i /= 10;
}
return sum;
}
}
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则之后不能再次进入这个格子。 例如 a b c e s f c s a d e e 这样的3 X 4 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
/**
* Created by xx on 2018/9/28.
*/
public class news {
public static void main(String[] args) {
int n=20;
news obj = new news();
char[] xz= {'a','b','c','b','s','f','c','s','a','d','e','e'};
char[] xx = {'b','c','c','e','d'};
int rows = 3;
int cols = 4;
System.out.println(obj.hasPath(xz,rows,cols,xx));
}
public boolean hasPath(char[] matrix,int rows,int cols,char[] str){
if(matrix == null || matrix.length != rows * cols
|| str == null || str.length == 0
|| str.length > matrix.length) return false;
boolean[] visited = new boolean[matrix.length];
for (int j = 0; j < rows; j++) {
for (int i = 0; i < cols; i++) {//每个节点都有可能是起点
if(DFS(matrix,rows,cols,str,i,j,0,visited)) return true;
}
//这里多了个k=0来充当str的索引
}
return false;
}
private boolean DFS(char[] matrix, int rows, int cols, char[] str, int i, int j, int k,boolean[] visited){
if (i < 0 || i >= cols || j < 0 || j >= rows || visited[i + j * cols] || matrix[i + j * cols] != str[k])return false;
if(k == str.length - 1) return true;
visited[i + j * cols] = true;
if(DFS(matrix, rows, cols, str, i, j - 1, k + 1, visited)
|| DFS(matrix, rows, cols, str, i + 1, j, k + 1, visited)
|| DFS(matrix, rows, cols, str, i, j + 1, k + 1, visited)
|| DFS(matrix, rows, cols, str, i - 1, j, k + 1, visited))
return true;
visited[i + j * cols] = false;//归
return false;
}
}