13.機器人的運動範圍

13.機器人的運動範圍

題目和代碼來自書上

以下是牛客網上ac過的代碼

class Solution {
public:
    int movingCount(int threshold, int rows, int cols)
    {
        if (threshold < 0 || rows <= 0 || cols <= 0) return 0;
        vector<vector<bool>> visited;
        for (int i = 0; i < rows; i++ ) {
            vector<bool> tmp_rows(cols,false);
            visited.push_back(tmp_rows);
        }

        int ret = movingCountCore(threshold, rows, cols,0,0, visited);
        return ret;
    }

    int movingCountCore(int threshold, int rows, int cols, int i, int j, vector<vector<bool>>& visited ) {
        int count = 0;
        if (check(threshold, i,j, rows, cols,visited)) {
            visited[i][j] = true;
            count = 1 + movingCountCore(threshold, rows, cols, i+1, j, visited)
                + movingCountCore(threshold, rows, cols, i-1, j, visited)
                + movingCountCore(threshold, rows, cols, i, j+1, visited)
                + movingCountCore(threshold, rows, cols, i, j-1, visited);
        }
        return count;
    }
    int check(int threshold, int i, int j, int rows, int cols, vector<vector<bool>>& visited) {
        if (i >= 0 && i < rows
           && j >= 0 && j < cols
           && !visited[i][j]
           && get_num(i) + get_num(j) <= threshold) {
            return true;
        }
        return false;
    }
    int get_num(int num) {
        int sum = 0;
        while(num>0) {
            sum += num % 10;
            num /= 10;
        }
        return sum;
    }
};

最近比較忙,練的題目比較少,要加油啊!!
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章