劍指offer13——機器人的運動範圍

題目描述

地上有一個m行和n列的方格。一個機器人從座標0,0的格子開始移動,每一次只能向左,右,上,下四個方向移動一格,但是不能進入行座標和列座標的數位之和大於k的格子。 例如,當k爲18時,機器人能夠進入方格(35,37),因爲3+5+3+7 = 18。但是,它不能進入方格(35,38),因爲3+5+3+8 = 19。請問該機器人能夠達到多少個格子?

 

題目分析


class Solution {
public:
    int movingCount(int threshold, int rows, int cols)
    {
        if(threshold < 0 || rows <= 0 || cols <= 0)
            return 0;
        bool *visited = new bool[rows * cols];
        for(int i=0; i < rows*cols; ++i)
            visited[i] = false;
         
        int count = movingCountCore(threshold, rows, cols, 0, 0, visited);
         
        delete[] visited;
         
        return count;
    }
    
    int movingCountCore(int threshold, int rows, int cols, int row, int col, bool *visited){
        int count = 0;
        if(check(threshold, rows, cols, row, col, visited)){  //判斷機器人能否進入座標爲(row, col)的方格
            visited[row*cols + col] = true;
            count = 1 + movingCountCore(threshold, rows, cols, row-1, col, visited)
                      + movingCountCore(threshold, rows, cols, row+1, col, visited)
                      + movingCountCore(threshold, rows, cols, row, col-1, visited)
                      + movingCountCore(threshold, rows, cols, row, col+1, visited);
        }
        return count;
    }
    
    //判斷機器人能否進入座標爲(row, col)的方格
    bool check(int threshold, int rows, int cols, int row, int col, bool* visited){
        if(row >= 0 && row < rows && col >= 0 && col < cols && getDigitSum(row) + getDigitSum(col) <= threshold && !visited[row*cols + col])
            return true;
         
        return false;
    }
    
    int getDigitSum(int number){
        int sum = 0;
        while(number > 0){
            sum += number % 10;
            number /= 10;
        }
        return sum;
    }
    
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章