zoukankan      html  css  js  c++  java
  • 剑指offer系列——66.机器人的运动范围

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

        int movingCount(int threshold, int rows, int cols) {
            bool *array = new bool[rows * cols];
            for (int i = 0; i < rows * cols; i++)
                array[i] = true;
            //从起点开始即可
            return getCount(threshold, 0, 0, rows, cols, array);
        }
    
        int getCount(int threshold, int i, int j, int rows, int cols, bool *array) {
            int index = i * cols + j;
            if (i < 0 || j < 0 || i >= rows || j >= cols || !array[index] || addSum(i) + addSum(j) > threshold)
                return 0;
            //走过就不会再经过了
            array[index] = false;
            return 1 + getCount(threshold, i - 1, j, rows, cols, array) + getCount(threshold, i + 1, j, rows, cols, array) +
                   getCount(threshold, i, j - 1, rows, cols, array) + getCount(threshold, i, j + 1, rows, cols, array);
        }
    
        int addSum(int i) {
            int sum = 0;
            while (i) {
                sum += i % 10;
                i = i / 10;
            }
            return sum;
        }
    
  • 相关阅读:
    ssd笔记
    深度学习 参数笔记
    NVIDIA驱动安装
    下载大文件笔记
    vue中使用echart笔记
    torch.no_grad
    暑期第二周总结
    暑期第一周总结
    第十六周学习进度
    期末总结
  • 原文地址:https://www.cnblogs.com/xym4869/p/12391142.html
Copyright © 2011-2022 走看看