劍指offer 面試題13 機械人的運動範圍

2021-09-25 03:38:38 字數 1142 閱讀 8089

題目:地上有乙個m行和n列的方格。乙個機械人從座標0,0的格仔開始移動,每一次只能向左,右,上,下四個方向移動一格,但是不能進入行座標和列座標的數字之和大於k的格仔。 例如,當k為18時,機械人能夠進入方格(35,37),因為3+5+3+7 = 18。但是,它不能進入方格(35,38),因為3+5+3+8 = 19。請問該機械人能夠達到多少個格仔?

注意第10行i/10.0>=0.1,若直接寫成10,在python2下執行錯誤。

思路:回溯法,只判斷向右向下這兩個方向。

class solution:

def movingcount(self, threshold, rows, cols):

self.row = rows

self.col = cols

list_=

self.search(list_, threshold, 0, 0)

return len(list_)

def sum(self, sum, i):

while i / 10.0 >= 0.1:

sum += i % 10

i = int(i / 10)

return sum

def check(self, i, j, threshold):

sum=0

sum = self.sum(sum, i)

sum = self.sum(sum, j)

if sum <= threshold:

return true

else:

return false

def search(self, dict_, threshold, i, j):

if not self.check(i, j, threshold) or (i, j) in dict_:

return

if j != self.col-1 and self.check(i, j+1, threshold):

self.search(dict_, threshold, i, (j+1))

if i != self.row-1and self.check(i+1, j, threshold):

self.search(dict_, threshold, (i+1), j)

劍指offer 面試題13 機械人的運動範圍

地上有乙個m行n列的方格。乙個機械人從座標 0,0 的格仔開始移動,它每次可以向左,向右,向上,向下移動一格,但不能進入行座標和列座標的位數之和大於k的格仔。例如 當k為18時,機械人能夠進入方格 35,37 因為3 5 3 7 18 但它不能進入方格 35,38 因為3 5 3 8 19.請問該機...

劍指offer面試題13 機械人的運動範圍

地上有乙個m行和n列的方格。乙個機械人從座標0,0的格仔開始移動,每一次只能向左,右,上,下四個方向移動一格,但是不能進入行座標和列座標的數字之和大於k的格仔。例如,當k為18時,機械人能夠進入方格 35,37 因為3 5 3 7 18。但是,它不能進入方格 35,38 因為3 5 3 8 19。請...

劍指offer 面試題13 機械人的運動範圍

地上有乙個m行n列的方格,從座標 0,0 到座標 m 1,n 1 乙個機械人從座標 0,0 的格仔開始移動,它每次可以向左 右 上 下移動一格 不能移動到方格外 也不能進入行座標和列座標的數字之和大於k的格仔。例如,當k為18時,機械人能夠進入方格 35,37 因為3 5 3 7 18。但它不能進入...