zoukankan      html  css  js  c++  java
  • 剑指offer-面试题13-机器人的运动范围-递归法

    /*
    题目:
    	地上有一个m行n列的方格。一个机器人从坐标(0,0)的格子开始运动,
    	每次可向上、下、左、右移动一格,但不能进入行坐标和列坐标之和大于k的格子。
    	如,当k=18时,机器人能进入(35,37),因为3+5+3+7=18。
    	但不能进入(35,38),问机器人能够到达多少格子。
    */
    /*
    思路:
    	递归法。
    	机器人从第一个格子走;
    	计算机器人向左、右、上、下可走的格子数之和。
    	使用visited进行标注,防止已走过的格子被重复计数。
    	
    */
    
    #include<iostream>
    #include<string.h>
    #include<algorithm>
    using namespace std;
    bool isValid(int row,int col,int threshold){
        int num = 0;
        while(row != 0){
            num += row % 10;
            row = row / 10;
        }
        while(col != 0){
            num += col % 10;
            col = col / 10;
        }
        return num > threshold ? false : true;
    }
    int movingCounCore(int row,int col,int rows,int cols,int threshold,bool* visited){
        int myCount = 0;
        //cout<<row<<" "<<col<<endl;
        if(row >= 0 && col >=0 && row < rows && col < cols && !visited[cols*row+col] && isValid(row,col,threshold)){
            visited[row*cols + col] = true;
            myCount = 1+movingCounCore(row+1,col,rows,cols,threshold,visited) + movingCounCore(row,col+1,rows,cols,threshold,visited) +
                               movingCounCore(row-1,col,rows,cols,threshold,visited) + movingCounCore(row,col-1,rows,cols,threshold,visited);
        }
        return myCount;
    
    }
    int movingCount(int threshold,int rows,int cols){
        if(threshold < 0 || rows <= 0 || cols <= 0){
            return 0;
        }
        bool *visited = new bool[rows*cols];
        memset(visited,false,rows*cols);
        int myCount = movingCounCore(0,0,rows,cols,threshold,visited);
        delete[] visited;
        return myCount;
    }
    
    
    
    int main(){
        cout<<movingCount(5,2,2)<<endl;
    }
    

       

  • 相关阅读:
    经典排序算法--快速排序
    经典排序算法——希尔排序
    经典排序算法——插入排序
    经典排序算法——选择排序
    经典排序算法——冒泡排序
    java递归求八皇后问题解法
    学习当前流行框架,同时也要自己去造建议的框架
    如何提高服务器并发处理能力
    数据的校验和空指针
    编写程序流程
  • 原文地址:https://www.cnblogs.com/buaaZhhx/p/11845170.html
Copyright © 2011-2022 走看看