zoukankan      html  css  js  c++  java
  • 剑指offer面试题67:机器人的运动范围

    这道题又是一道回溯算法的问题。关于回溯算法,并不是特别擅长,这道题真的是不错的练手题目。可以通过这道题更加深刻的理解下回溯算法是怎么回事。

    这道题一开始有几个疑惑的地方,就是回溯的时候怎么处理有的点进行了多次递归的问题。答案之中用了一个动态数组就轻松解决了这个问题。

    这道题可以用四个函数来解决这个问题。

    看完书上的内容,代码成功的默写出来了。代码如下:

    //函数入口。
    int MovingCount(int threshhold, int rows, int columns)
    {
        bool* HasVisited = new bool[rows*columns];
        for (int i = 0; i < rows*columns; ++i)
        {
            HasVisited[i] = false;
        }
        int count = MovingCount(threshhold, rows, columns, 0, 0, HasVisited);
        delete[] HasVisited;
        return count;
    }
    
    //进行递归算法的核心代码
    int MovingCount(int threshhold, int rows, int columns, int row, int column, bool* HasVisited)
    {
        int count = 0;
    
        if (check(threshhold, rows, columns, row, column, HasVisited))
        {
            HasVisited[row*columns + column] = true;
    
            count = 1 + MovingCount(threshhold, rows, columns, row - 1, column, HasVisited) + MovingCount(threshhold, rows, columns, row, column - 1, HasVisited) + MovingCount(threshhold, rows, columns, row + 1, column, HasVisited) + MovingCount(threshhold, rows, columns, row, column + 1, HasVisited);
        }
    
        return count;
    }
    
    //判断这个点是否合适
    bool check(int threshhold, int rows, int columns, int row, int column, bool* HasVisited)
    {
        if (row < rows&&column < columns&&HasVisited[row*columns + column] == false && GetDigitNum(row) + GetDigitNum(column) <= threshhold)
            return true;
        else
            return false;
    }
    
    int GetDigitNum(int number)
    {
        int sum = 0;
        while (number > 0)
        {
            sum += number % 10;
            number /= 10;
        }
        return sum;
    }

    现在已经基本上理解了这道题的意思了。感觉还不错。不过,有一点要注意,一定要找时间复习一下。很容易忘记的。

  • 相关阅读:
    黑马day07 注册案例(二)
    LeetCode--Best Time to Buy and Sell Stock (贪心策略 or 动态规划)
    让UIView窄斜
    Android Material Design-Creating Lists and Cards(创建列表和卡)-(三)
    c#为了实现自己的线程池功能(一)
    4、应用程序设置应用程序详细信息页面
    【NIO】dawn在buffer用法
    《ArcGIS Runtime SDK for .NET开发笔记》--在线编辑
    ArcGIS Runtime SDK for .NET (Quartz Beta)之连接ArcGIS Portal
    《ArcGIS Runtime SDK for .NET开发笔记》--三维功能
  • 原文地址:https://www.cnblogs.com/chengxuyuanxiaowang/p/4300326.html
Copyright © 2011-2022 走看看