剑指Offer面试题13:机器人的运动范围 Java实现

剑指Offer 面试题13:机器人的运动范围

原题描述:

面试题13:机器人的运动范围

地上有一个m行n列的方格,机器人从坐标(0,0)的各自开始移动,每次可以往上下左右移动一格,但不能进入行列坐标的数位之和大于k的格子。问机器人能够达到多少个格子。


这题还是用回溯法解决问题,直接上Java代码了!


/**
	 * @param threshold 行列坐标的数位之和限制
	 * @param rows 方格行数
	 * @param cols 方格列数
	 * @return 能够到达的格子数
	 */
	public static int movingCount(int threshold, int rows, int cols) {
		if (threshold < 0 || rows <= 0 || cols <= 0) {
			return 0;
		}

		boolean[] visited = new boolean[rows * cols];
		int count = movingCountCore(threshold, rows, cols, 0, 0, visited);
		return count;
	}

/**
 * @param threshold
 * @param rows
 * @param cols
 * @param row 准备进入的格子行坐标
 * @param col 准备进入的格子列坐标
 * @param visited 标记每个格子是否已经记录过
 * @return
 */
	private static int movingCountCore(int threshold, int rows, int cols, int row, int col, boolean[] visited) {
		int count = 0;
		if (check(threshold, rows, cols, row, col, visited)) {
			visited[row * cols + col] = true;

			count = 1 + movingCountCore(threshold, rows, cols, row - 1, col, visited)
					+ movingCountCore(threshold, rows, cols, row, col - 1, visited)
					+ movingCountCore(threshold, rows, cols, row + 1, col, visited)
					+ movingCountCore(threshold, rows, cols, row, col + 1, visited);
		}
		return count;
	}

	//判断这个方格是否满足访问条件
	private static boolean check(int threshold, int rows, int cols, int row, int col, boolean[] visited) {
		if (row >= 0 && row < rows && col >= 0 && col < cols && getDigitSum(row) + getDigitSum(col) <= threshold
				&& !visited[row * cols + col])
			return true;

		return false;
	}


//计算下标各位数和
	private static int getDigitSum(int number) {
		int sum = 0;
		while (number > 0) {
			sum += number % 10;
			number /= 10;
		}
		return sum;
	}
测试代码如下:

public static void main(String[] args) {
		int [] kArr={0,1,2,3,4};
		int [] result=new int[kArr.length];
		for(int i=0;i<kArr.length;i++){
			result[i]=movingCount(kArr[i],3,6);
		}
		String s=Arrays.toString(result);
		System.out.println(s);
	}

输出结果为:[1, 3, 6, 9, 12]

做了Offer上两道回溯法的题目,但对这个概念还是有点蒙。立个flag,这个周末专门捋一下这个思想。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值