1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| class Solution { public: int movingCount(int threshold, int rows, int cols) { if(threshold <= 0 || rows <=0 || cols <= 0){ return 0; } bool *flags = new bool[rows*cols]; for(int i = 0; i < rows * cols; i++){ flags[i] = false; } return helper(threshold,rows,cols,0,0,flags); } int helper(int threshold,int rows,int cols,int i,int j,bool *flags){ int res = 0; if(checkToGo(threshold,rows,cols,i,j,flags)){ flags[i*cols+j] = true; res = 1+helper(threshold,rows,cols,i+1,j,flags) +helper(threshold,rows,cols,i-1,j,flags) +helper(threshold,rows,cols,i,j+1,flags) +helper(threshold,rows,cols,i,j-1,flags); } return res; } bool checkToGo(int threshold,int rows,int cols,int i,int j,bool *flags){ if(i>=0 && i<rows && j>=0 && j<cols && checkThreshold(threshold,i,j) && flags[i*cols+j] == false){ return true; } return false; } bool checkThreshold(int threshold,int i,int j){ int temp = 0; while(i){ temp += i%10; i = i/10; } while(j){ temp += j%10; j = j/10; } return temp<=threshold; } private: };
|