剑指offer13 机器人的运动范围
public class Solution { public int movingCount(int threshold, int rows, int cols) { if(rows<1||cols<1||threshold<0) return 0; boolean[][] reached = new boolean[rows][cols]; int[] count = new int[1];count[0]=0; getCount(threshold,rows,cols,0,0,reached,count); return count[0]; } private void getCount(int threshold,int rows,int cols,int row,int col,boolean[][] reached,int[] count){ if(!isReachable(threshold,rows,cols,row,col)||reached[row][col]) return; reached[row][col]=true; count[0]=count[0]+1; getCount(threshold,rows,cols,row+1,col,reached,count); getCount(threshold,rows,cols,row-1,col,reached,count); getCount(threshold,rows,cols,row,col+1,reached,count); getCount(threshold,rows,cols,row,col-1,reached,count); } private boolean isReachable(int threshold,int rows,int cols,int row,int col){ if(row<0||row>=rows||col<0||col>=cols) return false; int sum = getSum(col)+getSum(row); if(sum>threshold) return false; return true; } private int getSum(int num){ int sum = 0; while(num!=0){ sum+=num%10; num/=10; } return sum; } }
运行时间:14ms
占用内存:9416k
# -*- coding:utf-8 -*- class Solution: def movingCount(self, threshold, rows, cols): # write code here if threshold < 0 or rows<1 or cols<1: return 0 count = [0,] reached = [[False for i in range(cols)] for j in range(rows)] self.getCount(threshold,rows,cols,0,0,count,reached) return count[0] def getCount(self,threshold,rows,cols,row,col,count,reached): if row<0 or col<0 or row>=rows or col>=cols or reached[row][col]: return if self.digitcount(row)+self.digitcount(col)> threshold: return reached[row][col] = True count[0]+=1 self.getCount(threshold,rows,cols,row+1,col,count,reached) self.getCount(threshold,rows,cols,row-1,col,count,reached) self.getCount(threshold,rows,cols,row,col+1,count,reached) self.getCount(threshold,rows,cols,row,col-1,count,reached) def digitcount(self,num): ans = 0 while num>0: ans += num%10 num /= 10 return ans
运行时间:24ms
占用内存:5724k

浙公网安备 33010602011771号