做剑指offer的时候一点小疑惑(java)

题目描述
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?

--------------------------------------------------------------------

public class Solution {
/*

为什么不对????

static int num=0;
public int movingCount(int threshold, int rows, int cols)
{
boolean[][] flag=new boolean[rows][cols];
helper(threshold,0,0,rows,cols,flag);
return num;
}
public void helper(int threshold, int left,int right,int rows, int cols,boolean[][] flag){
if(left<0||left>=rows||right<0||right>=cols||flag[left][right]||!getsum(left,right,threshold))
return ;
flag[left][right]=true;
num++;
helper(threshold,left+1,right,rows,cols,flag);
helper(threshold,left-1,right,rows,cols,flag);
helper(threshold,left,right+1,rows,cols,flag);
helper(threshold,left,right-1,rows,cols,flag);

}*/
public int movingCount(int threshold, int rows, int cols)
{
boolean[][] flag=new boolean[rows][cols];
return helper(threshold,0,0,rows,cols,flag);
}
public int helper(int threshold, int left,int right,int rows, int cols,boolean[][] flag){
if(left<0||left>=rows||right<0||right>=cols||flag[left][right]||!getsum(left,right,threshold))
return 0;
flag[left][right]=true;

return 1+ helper(threshold,left+1,right,rows,cols,flag)
+helper(threshold,left-1,right,rows,cols,flag)
+helper(threshold,left,right+1,rows,cols,flag)
+helper(threshold,left,right-1,rows,cols,flag);

}
public boolean getsum(int left,int right,int threshold){
int sum=0;
while(left>0){
sum+=left%10;
left/=10;
}
while(right>0){
sum+=right%10;
right/=10;
}
return (sum>threshold)?false:true;
}

}

我用注释的地方为什么不对呢?下面就可以

全部评论
最开始的static int num=0; static 去掉试试,要么你就在movingCount方法里每次都先num=0;
点赞 回复 分享
发布于 2018-05-03 09:46
奇怪了 如果我还是加上static,  我在调用movingCount里面的helper的时候,如果在前面加上一个num=0,也可以通过编译。 弄不明白。。。。
点赞 回复 分享
发布于 2018-05-03 10:26
我用python按照楼主法1是对的。。Java不知道怎么回事,楼主找到问题了求告知谢谢~ # -*- coding:utf-8 -*- class Solution: def movingCount(self, threshold, rows, cols): self.count = 0 visited = [[True] * cols for _ in range(rows)] self.dfs(threshold, rows, cols, 0, 0, visited) return self.count def dfs(self, threshold, rows, cols, i, j, visited): if (0 <=i < rows and 0 <= j < cols and visited[i][j] and self.computeSum(i) + self.computeSum(j) <= threshold): visited[i][j] = False self.count += 1 self.dfs(threshold, rows, cols, i-1, j, visited) self.dfs(threshold, rows, cols, i+1, j, visited) self.dfs(threshold, rows, cols, i, j-1, visited) self.dfs(threshold, rows, cols, i, j+1, visited) def computeSum(self, num): res = 0 while num: res += num % 10 num //= 10 return res
点赞 回复 分享
发布于 2018-05-03 09:31

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务