编程练习--回溯法

编程练习–回溯法

回溯法,通过递归不断尝试,失败后返回到前一步继续尝试…

矩阵中的路径

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;
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值