劍指offer - 66機器人的運動範圍

題目描述

地上有一個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 getsum(int val){
        int sum = 0;
        while(val){
            sum += val % 10;
            val /= 10;
        }
        return sum;
    }
    //遞歸移動
    void moving(int threshold, int rows, int cols, int x, int y, bool* flags, int* count){
        if(x < 0 || x > rows-1){
            return;
        }
        if(y < 0 || y > cols-1){
            return;
        }
        if(flags[x*cols+y]){
            return;
        }
        if(getsum(x)+getsum(y) > threshold){
            return;
        }
        flags[x*cols+y] = true;
        (*count)++;
        moving(threshold, rows, cols, x+1, y, flags, count);
        moving(threshold, rows, cols, x-1, y, flags, count);
        moving(threshold, rows, cols, x, y+1, flags, count);
        moving(threshold, rows, cols, x, y-1, flags, count);        
    }
    //使用flags標記方格是否已經走過    
    int movingCount(int threshold, int rows, int cols)
    {
        int count = 0;
        bool* flags = new bool[rows*cols];
                for(int i = 0; i < rows*cols; i++){
            flags[i] = false;
        }
        moving(threshold, rows, cols, 0, 0, flags, &count);
        return count;
    }
};

 

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