class Solution { public: int count=0;int numSum(int num) { int rev=0; while(num) { rev+=num%10; num=num/10; } return rev; } void fun(int x,int y,int threshold,int rows,int cols,bool * flags) { if(x<0||y<0||x>=rows||y>=cols||flags[x*cols+y]) return; if(flags[x*cols+y]==false&&(numSum(x)+numSum(y)<=threshold) ) { flags[x*cols+y]=true; count++; fun(x+1,y,threshold,rows,cols,flags); fun(x-1,y,threshold,rows,cols,flags); fun(x,y+1,threshold,rows,cols,flags); fun(x,y-1,threshold,rows,cols,flags); } } int movingCount(int threshold, int rows, int cols) { bool * flags=new bool[rows*cols]; for(int i=0;i<rows;i++) { for(int j=0;j<cols;j++) flags[i*cols+j]=false; } fun(0,0,threshold,rows,cols,flags); return count; } };
原文:https://www.cnblogs.com/JsonZhangAA/p/12153594.html