首页 > 其他 > 详细

面试题13:机器人的运动范围

时间:2020-07-17 15:05:32      阅读:43      评论:0      收藏:0      [点我收藏+]

本题考察的是回溯算法,可以使用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;
}

面试题13:机器人的运动范围

原文:https://www.cnblogs.com/flyingrun/p/13328476.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!