• 机器人的运动范围


    题目描述

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

    代码

    class Solution {
    public:
        int movingCount(int threshold, int rows, int cols)
        {
            vector<vector<int>> visited(rows, vector<int>(cols, 0));
            return movingCount(threshold, rows, cols, 0, 0, visited);
        }
        
        int movingCount(int t, int r, int c, int x, int y, vector<vector<int>> &v)
        {
            if (x < 0 || x >= r || y < 0 || y >= c) {
                return 0;
            }
            if (v[x][y]) {
                return 0;
            }
            if (sum(x) + sum(y) > t) {
                return 0;
            }
            v[x][y] = 1;
            
            return 1 + movingCount(t, r, c, x + 1, y, v) 
                + movingCount(t, r, c, x - 1, y, v) 
                + movingCount(t, r, c, x, y + 1, v) 
                + movingCount(t, r, c, x, y - 1, v);
        }
        int sum(int x) {
            int result = 0;
            while (x) {
                result += x % 10;
                x /= 10;
            }
            return result;
        }
    };
    
  • 相关阅读:
    【Android】开发优化之——调优工具:TrackView,Method Profiling
    MapReduce:具体解释Shuffle过程
    Kafka编程实例
    常用的语句
    CDN
    iOS中的固定 高度
    iPhone手机屏幕的尺寸180330更新
    UITextField
    iOS基本网络请求
    Xcode界面简介
  • 原文地址:https://www.cnblogs.com/jecyhw/p/6655103.html
Copyright © 2020-2023  润新知