import java.util.*; public class Solution { int[][] flag; int ans = 0, cols, rows, threshold; public int movingCount(int threshold, int rows, int cols) { flag = new int[rows][cols]; this.cols = cols; this.rows = rows; this.threshold = threshold; dfs(0, 0, 0, 0); return ans; } void dfs(int a, int b,int c,int d) { if (a >= rows || b >= cols || c + d > threshold || flag[a][b] == 1) { return; } ans++; flag[a][b] = 1; dfs(a + 1, b, (a + 1) % 10 == 0?c - 8:c + 1, d); dfs(a, b + 1, c, (b + 1) % 10 == 0?d - 8:d + 1); } }