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

    本题考察的是回溯算法,可以使用DFS解决问题。

    C++版本

    #include <iostream>
    #include <vector>
    using namespace std;
    
    int getDigitSum(int num){
        int sum = 0;
        while(num > 0){
            sum += num%10;
            num/=10;
        }
        return sum;
    }
    
    bool check(int threshold, int rows, int cols, int row, int col, bool visited[]){
        if(row>=0 && col>=0 && row < rows && col < cols && getDigitSum(row) + getDigitSum(col) <= threshold && !visited[row*cols+col])
            return true;
        return false;
    }
    
    int dfsmovingCountCore(int threshold, int rows, int cols, int row, int col, bool visited[]){
        int count = 0;
        if(check(threshold, rows, cols, row, col, visited)){
            visited[row*cols+col] = true;
            count = 1 + dfsmovingCountCore(threshold, rows, cols, row, col-1, visited)
            + dfsmovingCountCore(threshold, rows, cols, row, col+1, visited)
            + dfsmovingCountCore(threshold, rows, cols, row-1, col, visited)
            + dfsmovingCountCore(threshold, rows, cols, row+1, col, visited);
        }
        return count;
    }
    
    int movingCount(int threshold, int rows, int cols){
        if(threshold < 0 || rows < 1 || cols < 1)
            return 0;
        bool visited[rows*cols];
        memset(visited, false, sizeof(visited));
        int count = dfsmovingCountCore(threshold, rows, cols, 0, 0, visited);
        return count;
    }
    
    int main(){
        int a[5] = {1,2,3,4,5};
        cout<<&a[2]<<" "<<&a[3]<<endl;
        cout<<Fibonacci(6)<<endl;
        return 0;
    }
    
    
  • 相关阅读:
    Scrapy爬虫快速入门
    python垃圾回收机制
    django项目的uwsgi方式启停脚本
    hdu 5504 GT and sequence
    python 在 for i in range() 块中改变 i 的值的效果
    linux 在终端中打开图形化文件管理器
    apache 支持 php
    Mysql 学习记录
    git 导入代码到已有仓库
    python import 自己的包
  • 原文地址:https://www.cnblogs.com/flyingrun/p/13328476.html
Copyright © 2011-2022 走看看