劍指offer系列-面試題-13 - 機器人的運動範圍(python)

1. 題目

地上有一個m行n列的方格。一個機器人從座標(0, 0)的格子開始移動,它每次可以向左、右、上、下移動一格,但不能進入行座標和列座標的數位之後大於k的格子。例如,當k爲18時,機器人能夠進入方格(35, 37),因爲3+5+3+7=18。但它不能進入方法(35, 38),因爲3+5+3+8=19。請問該機器人能夠到達多少個格子?

2. 解題思路

詳情見 機器人的運動範圍

3. 代碼實現

3.1 BFS

def digitsum(n):
    ans = 0
    while n:
        ans += n % 10
        n //= 10
    return ans

class Solution:
    def movingCount(self, m: int, n: int, k: int) -> int:
        from queue import Queue
        q = Queue()
        q.put((0, 0))
        s = set()
        while not q.empty():
            x, y = q.get()
            if (x, y) not in s and 0 <= x < m and 0 <= y < n and digitsum(x) + digitsum(y) <= k:
                s.add((x, y))
                for nx, ny in [(x + 1, y), (x, y + 1)]:
                    q.put((nx, ny))
        return len(s)

4. 總結

so hard

5. 參考文獻

[1] 劍指offer叢書
[2] 劍指Offer——名企面試官精講典型編程題

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章