剑指offer--面试题13:机器人的运动范围

来源:互联网 发布:mobi 阅读软件 编辑:程序博客网 时间:2024/06/13 19:43

#include <stdio.h>#include<string.h>int CountCore(int k, int rows, int cols, int row, int col, bool* visited);int getDigitSum(int number);int Count(int k, int rows, int cols){    if(k < 0 || rows <= 0 || cols <= 0)        return 0;    bool *visited = new bool[rows * cols];memset(visited,false,rows*cols);    int count = CountCore(k, rows, cols,0, 0, visited);    delete[] visited;    return count;}int CountCore(int k, int rows, int cols, int row,int col, bool* visited){    int count = 0;    if(row >=0&&row<rows&&col>=0&&col<cols  &&  getDigitSum(row)+getDigitSum(col)<=k&&!visited[row* cols+col])    {        visited[row * cols + col] = true;        count = 1 + CountCore(k, rows, cols, row - 1, col, visited)  + CountCore(k, rows, cols, row, col - 1, visited)                  + CountCore(k, rows, cols, row + 1, col, visited)                  + CountCore(k, rows, cols, row, col + 1, visited);    }    return count;}int getDigitSum(int number){for(int sum=0;number>0;number /=10)sum+=number%10;    return sum;}int main(){    printf("阈值为0时,1行1列的方格,机器人能到达的格子数目为:%d \n",Count(0, 1, 1));printf("阈值为5时,10行10列的方格,机器人能到达的格子数目为:%d \n",Count(5, 10, 10));printf("阈值为15时,20行20列的方格,机器人能到达的格子数目为:%d \n",Count(15, 20, 20));printf("阈值为-10时,10行10列的方格,机器人能到达的格子数目为:%d \n",Count(-10, 10, 10));    return 0;}