zoukankan      html  css  js  c++  java
  • 机器人的运动范围

    题目描述

    地上有一个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;
        }
    }
    

    笔记

  • 相关阅读:
    1044 拦截导弹
    3060 抓住那头奶牛 USACO
    2727:仙岛求药(广搜)
    4906 删数问题(另一种贪心思路)
    1004 四子连棋
    1005 生日礼物
    1031 质数环
    1008 选数
    1073 家族
    2801 LOL-盖伦的蹲草计划
  • 原文地址:https://www.cnblogs.com/ustca/p/12761537.html
Copyright © 2011-2022 走看看