【算法题】机器人的运动范围

题目描述

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

分析
典型的DFS题。初始化一个布尔型二维map,从(0,0)开始,符合条件时,向下、右递归,并设此坐标为true且计数加1,若不符合条件结束递归(此路不通)。

代码(已AC)

public class Solution {
    int count=0;
    public int movingCount(int threshold, int rows, int cols)
    {
        boolean[][] map = new boolean[rows][cols];
        dfs(0,0,rows,cols,threshold,map);
        return count;
    }
    public void dfs(int i, int j, int rows, int cols, int threshold, boolean[][] map){
        if(i<0 || j<0 || i>=rows || j>=cols || map[i][j]) return;  // 不符合条件,递归结束
        if(validate(i,j,threshold)){
            map[i][j]=true;
            count++;    // 符合条件,计数加1,向下、右递归
            dfs(i+1, j, rows, cols, threshold, map);
            dfs(i, j+1, rows, cols, threshold, map);
        }

    }
    public boolean validate(int i, int j, int threshold){
        int total = 0;
        while(i!=0){
            total += i%10;
            i/=10;
        }
        while(j!=0){
            total += j%10;
            j/=10;
        }
        return total <= threshold;
    }
}
原创文章 28 获赞 22 访问量 5万+

猜你喜欢

转载自blog.csdn.net/Steven_L_/article/details/105919584