溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

python機器人運動范圍的示例分析

發(fā)布時間:2021-08-26 10:56:30 來源:億速云 閱讀:118 作者:小新 欄目:開發(fā)技術(shù)

這篇文章主要介紹python機器人運動范圍的示例分析,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

機器人的運動范圍Python實現(xiàn):

問題:地上有個 m 行 n 列的方格。一個機器人從坐標(0,0)的格子開始移動,它每一次可以向左、右、上、下移動一格,但不能進入行坐標和列坐標的數(shù)位之和大于 k 的格子。

例如,當 k 為 18 時,機器人能夠進入方格(35,37),因為 3+5+3+7=18 但它不能進入方格(35,38),因為 3+5+3+8=19 請問該機器人能夠達到多少格子?

回溯算法。

當準備進入坐標(i,j)時,通過檢查坐標的數(shù)位來判斷機器人能否進入。如果能進入的話,接著判斷四個相鄰的格子。

代碼:

# -*- coding:utf-8 -*-
class Solution:
 def movingCount(self, threshold, rows, cols):
  # write code here
  matrix = [[True for i in range(cols)] for j in range(rows)]
  result = self.findgrid(threshold, rows, cols, matrix, 0, 0)
  return result
 
 def judge(self, threshold, i, j):
  if sum(map(int,str(i)+str(j))) <= threshold:
   return True
  else:
   return False
  
 def findgrid(self, threshold, rows, cols, matrix, i, j):
  count = 0
  if i < rows and i>=0 and j<cols and j>=0 and self.judge(threshold, i, j) and matrix[i][j]:
   matrix[i][j] = False
   count = 1+ self.findgrid(threshold, rows, cols, matrix, i-1, j) \
     + self.findgrid(threshold, rows, cols, matrix, i+1, j) \
     + self.findgrid(threshold, rows, cols, matrix, i, j-1) \
     + self.findgrid(threshold, rows, cols, matrix, i, j+1)
  return count

以上是“python機器人運動范圍的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI