• 机器人的运动范围


    题目描述

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

    思路

    记忆化搜索。
    

    时间复杂度O(mn),空间复杂度O(mn)。

    代码

    public class Solution {
        private int k;
        private int count;
        private int row;
        private int col;
        private boolean[][] map;
        private int[][] step = new int[][] {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
        private boolean judge(int x, int y) {
            if(x < 0 || x >= row || y < 0 || y >= col || map[x][y]) {
                return false;
            }
            int sum = 0;
            while(x > 0) {
                sum += x % 10;
                x /= 10;
            }
            while(y > 0) {
                sum += y % 10;
                y /= 10;
            }
            return sum <= k;
        }
        public void move(int x, int y) {
            if(judge(x, y)) {
                count++;
                map[x][y] = true;
                for (int i = 0; i < 4; i++) {
                    int r = x + step[i][0];
                    int c = y + step[i][1];
                    if (judge(r, c)) {
                        move(r, c);
                    }
                }
            }
        }
        public int movingCount(int threshold, int rows, int cols)
        {
            if(threshold < 0 || rows < 1 || cols < 1) {
                return 0;
            }
            k = threshold;
            row = rows;
            col = cols;
            map = new boolean[rows][cols];
            move(0, 0);
            return count;
        }
    }
    

    笔记

  • 相关阅读:
    设计模式
    python高亮显示输出
    数据库入门3 数据库设计
    分支循环相关
    软件目录结构规范
    数据库入门2 数据库基础
    三级菜单
    字符串相关问题
    登录接口
    购物车
  • 原文地址:https://www.cnblogs.com/ustca/p/12761537.html
Copyright © 2020-2023  润新知