java代码
class Solution {
static boolean[][] st = new boolean[110][110];
static int count = 1;
public int movingCount(int threshold, int rows, int cols)
{
if(rows == 0 && cols == 0) return 0; //特判
int res = dfs(threshold, rows, cols, 0, 0);
return res;
}
private static int dfs(int k, int rows, int cols, int x, int y)
{
if(sum(x, y) > k) return 0;
st[x][y] = true;
int[] dx = {-1, 0, 1, 0}, dy = {0,1,0,-1};
for(int i = 0; i < 4; i ++)
{
int a = x + dx[i], b = y + dy[i];
if(a >= 0 && a < rows && b >= 0 && b < cols && sum(a, b) <= k && st[a][b] == false)
{
count ++;
dfs(k, rows, cols, a, b);
}
}
return count;
}
private static int sum(int x, int y) //求的是数位之和
{
int sum = 0;
while(x != 0)
{
sum += x % 10;
x /= 10;
}
while(y != 0)
{
sum += y % 10;
y /= 10;
}
return sum;
}
}
if(rows == 0 && cols == 0) return 0; 应该是if(rows == 0 || cols == 0) return 0;
不会超时吗?
第5个语句错了,应该是||,不是&&