"Sword Offer" Exercise - Interview Question 13 - Robot's Range of Motion

Question: There is a square with m rows and n columns on the ground. A robot starts to move from the grid of coordinates (0,0), and it can move one grid to the left, right, up, and down at a time, but cannot enter the grid where the sum of the digits of the row and column coordinates is greater than k. For example, when k is 18, the robot can enter square (35,37) because 3+5+3+7=18. But it cannot enter square (35,38) because 3+5+3+8=19. How many squares can the robot reach?

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("Please enter a threshold: ");
		int threshold = scanner.nextInt();

		System.out.print("Please enter the number of lines in the square: ");
		int rows = scanner.nextInt();

		System.out.print("Please enter the number of columns: ");
		int cols = scanner.nextInt();

		scanner.close();

		System.out.println("When k is " + threshold + ", the robot can reach " + sl.movingCount(threshold, rows, cols) + " cells.");
	}

	public int movingCount(int threshold, int rows, int cols) {
		// exception input
		if (threshold < 0 || rows < 0 || cols < 0)
			return 0;

		// store the previously reached position
		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;
	}

	// Determine whether the robot can enter a grid and its surroundings
	public int movingCountCore(int threshold, int rows, int cols, int row, int col, boolean[] visited) {
		int count = 0;

		// If the grid can be entered, then iteratively calculate whether the grid has access to the surrounding of this point, if possible, count the 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;
	}

	// Confirm whether you can enter the grid with coordinates (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;
	}

	// Calculate the sum of digits
	public int getDigitSum(int number) {
		int sum = 0;
		while (number > 0) {
			sum += number % 10;
			number /= 10;
		}

		return sum;
	}

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324778751&siteId=291194637