1. 程式人生 > >劍指offer--機器人的運動範圍

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

地上有一個m行和n列的方格。一個機器人從座標0,0的格子開始移動,每一次只能向左,右,上,下四個方向移動一格,但是不能進入行座標和列座標的數位之和大於k的格子。 例如,當k為18時,機器人能夠進入方格(35,37),因為3+5+3+7 = 18。但是,它不能進入方格(35,38),因為3+5+3+8 = 19。請問該機器人能夠達到多少個格子? 思路: 首先我們要設定一個函式,來確定這個格子是否可以進入。我這裡叫subnum,然後我們需要判斷邊界,這同樣是判斷能不能走的條件。然後如果可以走,+1,再判斷它的前後左右是否可以走。我們用一個二位陣列標記,走過的路,為了的不重複計數。 程式碼:

class Solution {
public:
    int SubNum(int num)
    {
        if(num < 10)
            return num;
        else return num%10+SubNum(num/10);
    }
    int CanInThisCount(int threshold,int row,int col,int rows,int cols,bool* arr)
    {
        if(row < 0 || row >= rows ||
           col < 0 || col >= cols ||
           (SubNum(row) + SubNum(col) > threshold) ||
           (arr[row + col*rows] == 1))
        {
            return 0;
        }
        else 
        {
            arr[row + col*rows] = 1;
            return 1 + CanInThisCount(threshold,row-1,col,rows,cols,arr)+
                       CanInThisCount(threshold,row,col-1,rows,cols,arr)+
                       CanInThisCount(threshold,row,col+1,rows,cols,arr)+
                       CanInThisCount(threshold,row+1,col,rows,cols,arr);
        }
    }
    int movingCount(int threshold, int rows, int cols)
    {
        bool* arr = new bool [rows*cols];
        memset(arr,0,sizeof(bool)*rows*cols);
        return CanInThisCount(threshold,0,0,rows,cols,arr);
    }
};