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;
    }
    
    
  • 相关阅读:
    [loj6271]生成树求和
    [cf1209E]Rotate Columns
    [cf1491H]Yuezheng Ling and Dynamic Tree
    [atARC064F]Rotated Palindromes
    [cf1491G]Switch and Flip
    [cf1491F]Magnets
    [atARC063F]Snuke's Coloring 2
    [atARC062F]Painting Graphs with AtCoDeer
    [atARC061F]Card Game for Three
    [atARC112E]Rvom and Rsrev
  • 原文地址:https://www.cnblogs.com/flyingrun/p/13328476.html
Copyright © 2011-2022 走看看