《剑指offer》练习-面试题13-机器人的运动范围

题目:地上有一个m行n列的方格。一个机器人从坐标(0,0)的格子开始移动,它每次可以向左、右、上、下移动一格,但不能进入行坐标和列坐标的数位之和大于k的格子。例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7=18。但它不能进入方格(35,38),因为3+5+3+8=19.请问该机器人能够到达多少个格子?

package offer;

import java.util.Scanner;

public class Solution13 {

	public static void main(String[] args) {

		Solution13 sl = new Solution13();
		Scanner scanner = new Scanner(System.in);

		System.out.print("请输入一个阈值:");
		int threshold = scanner.nextInt();

		System.out.print("请输入方格的行数:");
		int rows = scanner.nextInt();

		System.out.print("请输入方格的列数:");
		int cols = scanner.nextInt();

		scanner.close();

		System.out.println("当k为" + threshold + "时,机器人能够到达" + sl.movingCount(threshold, rows, cols) + "个格子。");
	}

	public int movingCount(int threshold, int rows, int cols) {
		// 异常输入
		if (threshold < 0 || rows < 0 || cols < 0)
			return 0;

		// 存储之前到达过的位置
		boolean[] visited = new boolean[rows * cols];

		for (int i = 0; i < rows * cols; ++i) {
			visited[i] = false;
		}
		int count = movingCountCore(threshold, rows, cols, 0, 0, visited);

		return count;
	}

	// 判断机器人能否进入某格子及其四周
	public int movingCountCore(int threshold, int rows, int cols, int row, int col, boolean[] visited) {
		int count = 0;

		// 如果这个格子可以进入,再迭代计算出这个格子已经这个点的四周能否进入,能则计数君count+1
		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 - 1, row, col, visited)
					+ movingCountCore(threshold, rows, cols, row + 1, col, visited)
					+ movingCountCore(threshold, rows, cols, row, col + 1, visited);

		}

		return count;
	}

	// 确认能否进入坐标为(row,col)格子
	public 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;
	}

	// 计算位数之和
	public int getDigitSum(int number) {
		int sum = 0;
		while (number > 0) {
			sum += number % 10;
			number /= 10;
		}

		return sum;
	}

}

猜你喜欢

转载自blog.csdn.net/sinat_34548226/article/details/80054895
今日推荐