编程练习–回溯法
回溯法,通过递归不断尝试,失败后返回到前一步继续尝试…
矩阵中的路径
public class Solution {
private int rows;
private int cols;
private boolean[] visited;
private int p;
public boolean hasPath(char[] matrix, int rows, int cols, char[] str)
{
this.rows = rows;
this.cols = cols;
this.p = 0;
this.visited = new boolean[matrix.length];
for(int i=0;i<visited.length;++i)
visited[i] = false;
//选择起点
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
if(hasPathCore(matrix,i,j,str)){
return true;
}
}
}
return false;
}
private boolean hasPathCore(char[]matrix,int i,int j,char[]str){
//查询到字符串最后一个
if(p==str.length){
return true;
}
//判断当前节点是否符合,符合进行下一步
boolean hasPath = false;
if(i>=0&&i<rows&&j>=0&&j<cols
&&matrix[i*cols+j]==str[p]
&&!visited[i*cols+j]){
p++;
visited[i*cols+j] = true;
hasPath = hasPathCore(matrix,i-1,j,str)||
hasPathCore(matrix,i+1,j,str)||
hasPathCore(matrix,i,j-1,str)||
hasPathCore(matrix,i,j+1,str);
if(!hasPath){
p--;
visited[i*cols+j] = false;
return false;
}
}
return hasPath;
}
}
机器人可以到达的格数
public class Robot {
private int threshold;
private int rows;
private int cols;
private int result = 0;
private boolean[] visited;
public int movingCount(int threshold, int rows, int cols)
{
this.threshold=threshold;;
this.rows = rows;
this.cols = cols;
this.visited = new boolean[rows*cols];
movingCore(0,0,visited);
return this.result;
}
private void movingCore(int i, int j, boolean[] visited) {
//判断当前节点是否符合
if(i<rows&&i>=0&&j<cols&&j>=0
&&isOK(i,j)&&!visited[i*cols+j]){
result++;
visited[i*cols+j] = true;
movingCore(i+1,j,visited);
movingCore(i-1,j,visited);
movingCore(i,j+1,visited);
movingCore(i,j-1,visited);
}
}
private boolean isOK(int i, int j) {
int sum = 0;
while(i>0){
sum += i%10;
i /= 10;
}
while(j>0){
sum += j%10;
j /= 10;
}
if(sum<=threshold)
return true;
else
return false;
}
}