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

劍指offer 12. 機器人的活動範圍

地上有一個m行和n列的方格。
一個機器人從座標0,0的格子開始移動,每一次只能向左,右,上,下四個方向移動一格。
但是不能進入行座標和列座標的數位之和大於k 的格子。
請問該機器人能夠達到多少個格子?

樣例1

輸入:k=7, m=4, n=5

輸出:20

樣例2

輸入:k=18, m=40, n=40

輸出:1484

解釋:當k為18時,機器人能夠進入方格(35,37),因為3+5+3+7 = 18。
      但是,它不能進入方格(35,38),因為3+5+3+8 = 19。

注意:

  1. 0<=m<=50
  2. 0<=n<=50
  3. 0<=k<=100

dfs入門題啊

class Solution {
public:
    int ans = 0;
    bool check(int k, int x, int y){
        int t = 0;
        while(x){
            t += x % 10;
            x /= 10;
        }
        while(y){
            t += y % 10;
            y /= 10;
        }
        return t <= k ? true : false;
    }
void dfs(int threshold, int rows, int cols, int x, int y, vector<vector<bool>>& visited){ int Next[4][2] = {0,1,0,-1,1,0,-1,0}; for(int k = 0; k < 4; k ++){ int nx = x + Next[k][0]; int ny = y + Next[k][1]; if(nx>=0 && ny>=
0 && nx < rows && ny < cols && !visited[nx][ny] && check(threshold, nx, ny)){ visited[nx][ny] = true; ans ++; dfs(threshold, rows, cols, nx, ny, visited); } } } int movingCount(int threshold, int rows, int cols) { vector<vector<bool>> visited(rows, vector<bool>(cols, false)); if(threshold < 1) return 1; if(!rows || ! cols) return rows + cols; visited[0][0] = true; ans ++; dfs(threshold, rows, cols, 0, 0, visited); return ans; } };