机器人的运动范围-剑指Offer

机器人的运动范围

题目描述

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

思路

  1. 这个跟“矩阵中的路径”那个题很相似,都是使用回溯法,不过这个题的起点是固定的,就是从(0,0)位置开始走
  2. 我们同样根据行数和列数创建一个矩阵,并且这个矩阵是包着边的矩阵,每个位置存储的是这个位置下标中每个位上的数的和,到时候直接比较即可
  3. 这个题目说的是能到达的最多的格子数,所以我们在弹栈的时候不用将结果减1,因为既然我们走过了就算“能到达”

代码

import java.util.Stack;
public class Solution {
    public int movingCount(int threshold, int rows, int cols)
    {
        int result = 0;
        if (threshold <= 0 || rows <= 0 || cols <= 0) {
        	return result;
        }
        int[][] data = new int[rows + 2][cols + 2];
        for (int i = 0; i < rows + 2; i++) {
        	for (int j = 0; j < cols + 2; j++) {
        		if (i == 0 || i == (rows + 1) || j == 0 || j == (cols + 1)) {
        			data[i][j] = -1;
        		} else {
        			data[i][j] = 0;
        			int rowVar = i - 1;
        			int colVar = j - 1;
        			while (rowVar > 0) {
        				data[i][j] += (rowVar % 10);
        				rowVar /= 10;
        			}
        			while (colVar > 0) {
        				data[i][j] += (colVar % 10);
        				colVar /= 10;
        			}
        		}
        	}
        }
        Stack stack = new Stack();
        boolean[][] flag = new boolean[rows + 2][cols + 2];
        for (int i = 0; i < rows + 1; i++) {
        	for (int j = 0; j < cols + 1; j++) {
        		flag[i][j] = true;
        	}
        }
        int[] init = {1, 1};
        flag[1][1] = false;
        stack.push(init);
        result++;
        while (!stack.isEmpty()) {
        	int[] temp = (int[])stack.peek();
        	int row = temp[0];
        	int col = temp[1];
        	if (data[row - 1][col] <= threshold && data[row - 1][col] > 0 && flag[row - 1][col] == true) {
        		int[] position = {row - 1, col};
        		stack.push(position);
        		flag[position[0]][position[1]] = false;
        		result++;
        	} else if (data[row][col + 1] <= threshold && data[row][col + 1] > 0 && flag[row][col + 1] == true) {
        		int[] position = {row, col + 1};
        		stack.push(position);
        		flag[position[0]][position[1]] = false;
        		result++;
        	} else if (data[row + 1][col] <= threshold && data[row + 1][col] > 0 && flag[row + 1][col] == true) {
        		int[] position = {row + 1, col};
        		stack.push(position);
        		flag[position[0]][position[1]] = false;
        		result++;
        	} else if (data[row][col - 1] <= threshold && data[row][col - 1] > 0 && flag[row][col - 1] == true) {
        		int[] position = {row, col - 1};
        		stack.push(position);
        		flag[position[0]][position[1]] = false;
        		result++;
        	} else {
        		stack.pop();
        	}
        }	
        return result;
    }
}
原文地址:https://www.cnblogs.com/rosending/p/5742725.html