機器人的運動範圍(C++遞歸的方式)

題目描述

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

思路

碰到這種題毫無疑問就是動態規劃或者遞歸。接下來就是考慮出口入口。
1》出口可以由題目得當座標和大於k值時,當該方格被移動過的時候,當座標大小超過m行和n列的方格座標範圍時,皆返回0.
2》除了這些情況就是向左,右,上,下四個方向移動一格。
3》還是設計一個tag標籤數組來記錄該方格是否被走過。

代碼

class Solution {
public:
    //int movepath(int threshold, int r, int c,int *tag);
    int movingCount(int threshold, int rows, int cols)
    {
        m = rows, n = cols;
        int *tag=new int[rows*cols];//標籤數組
        memset(tag, 0, rows * cols);//初始化標籤數組爲0
        if (rows == 0 || cols == 0)
            return 0;
        return movepath(threshold, 0, 0, tag);
        delete []tag;//防止內存泄露
    }
    int movepath(int threshold, int r, int c, int* tag) {
        //計算座標和。
        int sum = 0;
        int tmpr = r, tmpc = c;
        while (tmpr > 0 ) {
            sum += tmpr % 10;
            tmpr = tmpr / 10;	
        }
        while (tmpc > 0) {
            sum += tmpc % 10;
            tmpc = tmpc / 10;
        }
        //出口可以由題目得當座標和大於k值時,當該方格被移動過的時候,當座標大小超過m行和n列的方格座標範圍時,皆返回0.
        if (sum > threshold || r < 0 || c < 0 || r >= m || c >= n|| tag[r * n + c] ==1)
            return 0;
        //向左,右,上,下四個方向移動一格。
        tag[r * n + c]=1;//表示這個方格走過
        return movepath(threshold, r - 1, c, tag) + movepath(threshold, r, c - 1, tag) + movepath(threshold, r + 1, c, tag) + movepath(threshold, r, c + 1, tag) + 1;
    }
private:
     int m, n;//表示m行和n列的方格。減少函數參數數量。
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章