#include <vector> class Solution { public: int dir[4][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} }; int res = 0; int cal(int n) { int sum = 0; while(n) { sum += n % 10; n /= 10; } return sum; } void dfs(int i, int j, int rows, int cols, int threshold, vector<vector<bool>>& vis) { if(vis[i][j] || i < 0 || j < 0 || i >= rows || j >= cols) return; if(cal(i) + cal(j) > threshold) return; res ++; vis[i][j] = true; for(int k = 0; k < 4; k ++) { dfs(i + dir[k][0], j + dir[k][1], rows, cols, threshold, vis); } } int movingCount(int threshold, int rows, int cols) { if(threshold <= 0) return 1; vector<vector<bool> > vis(rows, vector<bool>(cols, false)); dfs(0, 0, rows, cols, threshold, vis); return res; } };