zoukankan      html  css  js  c++  java
  • 剑指Offer-66.机器人的运动范围(C++/Java)

    题目:

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

    分析:

    机器人从0,0出发,每次都要判断走的格子是否越界,或者已经走过了,或者超过了限制,如果符合条件的话,就从上下左右四个方向继续搜索即可。

    程序:

    C++

    class Solution {
    public:
        int movingCount(int threshold, int rows, int cols)
        {
            vector<vector<int>> visit(rows, vector<int>(cols, 0));
            int count = helper(threshold, 0, 0, visit);
            return count;
        }
        int helper(int threshold, int x, int y, vector<vector<int>> &visit){
            int c = 0;
            if(x < 0 || x > visit.size()-1 || y < 0 || y > visit[0].size()-1 || (getSum(x)+getSum(y)) > threshold || visit[x][y] == 1){
                return 0;
            }
            visit[x][y] = 1;
            c = 1 + helper(threshold, x+1, y, visit) + helper(threshold, x-1, y, visit) + helper(threshold, x, y+1, visit) + helper(threshold, x, y-1, visit);
            return c;
        }
        int getSum(int x){
            int sum = 0;
            while(x){
                sum += x % 10;
                x /= 10;
            }
            return sum;
        }
    };

    Java

    public class Solution {
        public int movingCount(int threshold, int rows, int cols)
        {
            int [][] visit = new int[rows][cols];
            int count = helper(threshold, 0, 0, visit);
            return count;
        }
        public int helper(int threshold, int x, int y, int[][] visit){
            int c = 0;
            if(x < 0 || x > visit.length-1 || y < 0 || y > visit[0].length-1 || (getSum(x)+getSum(y)) > threshold || visit[x][y] == 1){
                return 0;
            }
            visit[x][y] = 1;
            c = 1 + helper(threshold, x+1, y, visit) + helper(threshold, x-1, y, visit) + helper(threshold, x, y+1, visit) + helper(threshold, x, y-1, visit);
            return c;
        }
        int getSum(int x){
            int sum = 0;
            while(x != 0){
                sum += x % 10;
                x /= 10;
            }
            return sum;
        }
    }
  • 相关阅读:
    Oracle 12C 物理Standby 主备切换switchover
    Oracle 性能之 Enq: CF
    dyld: Library not loaded: /usr/local/opt/readline/lib/libreadline.7.dylib
    OGG 从Oracle备库同步数据至kafka
    WARNING: inbound connection timed out (ORA-3136)
    11G 新特性之 密码延迟认证
    org-mode 写 cnblogs 博客
    inner join, left join, right join, full outer join的区别
    Emacs 浏览网页
    服务器被攻击后当作矿机,高WIO
  • 原文地址:https://www.cnblogs.com/silentteller/p/12124725.html
Copyright © 2011-2022 走看看