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;
    }
    
    
  • 相关阅读:
    HDU 1850 Being a Good Boy in Spring Festival
    UESTC 1080 空心矩阵
    HDU 2491 Priest John's Busiest Day
    UVALive 6181
    ZOJ 2674 Strange Limit
    UVA 12532 Interval Product
    UESTC 1237 质因子分解
    UESTC 1014 Shot
    xe5 android listbox的 TMetropolisUIListBoxItem
    xe5 android tts(Text To Speech)
  • 原文地址:https://www.cnblogs.com/flyingrun/p/13328476.html
Copyright © 2011-2022 走看看