1 class Solution { 2 private: 3 int add(int n) 4 { 5 int sum =0; 6 while(n != 0) 7 { 8 sum += n%10; 9 n = n/10; 10 } 11 return sum; 12 } 13 int move(int threshold, int rows, int cols, int row, int col, int& count, vector<int>&visited) 14 { 15 if(row>=0 && row<rows && col>=0 && col<cols &&visited[row*cols+col]==0 && 16 add(row)+add(col)<=threshold) 17 { 18 visited[row*cols+col]=1; 19 count++; 20 move(threshold, rows, cols, row-1, col, count, visited); 21 move(threshold, rows, cols, row, col+1, count, visited); 22 move(threshold, rows, cols, row+1, col, count, visited); 23 move(threshold, rows, cols, row, col-1, count, visited); 24 } 25 26 return count; 27 } 28 public: 29 int movingCount(int threshold, int rows, int cols) 30 { 31 vector<int> visited(rows*cols,0); 32 int count = 0, col = 0, row = 0; 33 // visited[0] = 1; 34 return move(threshold, rows, cols, row, col, count, visited); 35 } 36 };