python機(jī)器人運(yùn)動范圍問題的解答
機(jī)器人的運(yùn)動范圍Python實(shí)現(xiàn):
問題:地上有個(gè) m 行 n 列的方格。一個(gè)機(jī)器人從坐標(biāo)(0,0)的格子開始移動,它每一次可以向左、右、上、下移動一格,但不能進(jìn)入行坐標(biāo)和列坐標(biāo)的數(shù)位之和大于 k 的格子。
例如,當(dāng) k 為 18 時(shí),機(jī)器人能夠進(jìn)入方格(35,37),因?yàn)?3+5+3+7=18 但它不能進(jìn)入方格(35,38),因?yàn)?3+5+3+8=19 請問該機(jī)器人能夠達(dá)到多少格子?
回溯算法。
當(dāng)準(zhǔn)備進(jìn)入坐標(biāo)(i,j)時(shí),通過檢查坐標(biāo)的數(shù)位來判斷機(jī)器人能否進(jìn)入。如果能進(jìn)入的話,接著判斷四個(gè)相鄰的格子。
代碼:
# -*- 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
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python3使用騰訊企業(yè)郵箱發(fā)送郵件的實(shí)例
今天小編就為大家分享一篇python3使用騰訊企業(yè)郵箱發(fā)送郵件的實(shí)例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-06-06Python異常對代碼運(yùn)行性能的影響實(shí)例解析
這篇文章主要介紹了Python異常對代碼運(yùn)行性能的影響實(shí)例解析,分享了相關(guān)代碼示例,小編覺得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-02-02