题目描述

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

  1. public int count = 0;//用来保存访问格子数
  2. public int movingCount(int threshold, int rows, int cols)
  3. {
  4. boolean[][] vis = new boolean[rows][cols];
  5. solve(threshold,rows,cols,0,0,vis);
  6. return count;
  7. }
  8. private void solve(int threshold, int rows,int cols,int x, int y,boolean[][] vis) {
  9. if(x<0||x>=rows||y<0||y>=cols||vis[x][y]||isThreshold(threshold,x,y)) {
  10. return;
  11. }
  12. vis[x][y] = true;
  13. count++;//如果格子坐标数位和不符合要求那么不会执行到这一行代码在上面就return了
  14. solve(threshold, rows,cols,x+1, y,vis);
  15. solve(threshold, rows,cols,x-1,y,vis);
  16. solve(threshold, rows,cols,x, y+1,vis);
  17. solve(threshold, rows,cols,x, y-1,vis);
  18. }
  19. public boolean isThreshold(int threshold,int x,int y) {
  20. int temp=0;
  21. while(x%10!=0) {
  22. temp+=x%10;
  23. x=x/10;
  24. }
  25. while(y%10!=0) {
  26. temp+=y%10;
  27. y=y/10;
  28. }
  29. if(temp>threshold) {
  30. return true;
  31. }
  32. return false;
  33. }