class Solution { public: int movingCount(int threshold, int rows, int cols) { if(threshold<0) return 0; row = rows; col = cols; ct= 1 ; memset(ma, 0, sizeof(ma)); ma[0][0] = 1; dfs(threshold,0,0); return ct; } void dfs(int k, int rr ,int cc) { for(int i=0; i<4; i++) { int c = dir[i][0] + cc; int r = dir[i][1] + rr; if(ma[r][c]==1 || c <0 || r<0 || c>=col || r>=row || sum_n(c, r) > k) continue; ma[r][c] = 1; ++ct; dfs(k, r, c); } } int sum_n(int a, int b) { int sumab = 0; while (a != 0) { sumab += a%10;; a /= 10; } while (b != 0) { sumab += b%10;; b /= 10; } return sumab; } private: int dir[4][2] = {{0,1},{0,-1},{1,0},{-1,0}}; int ma[80][80]; int row, col, ct; };
原文:https://www.cnblogs.com/evidd/p/10631653.html