题目:原题链接(中等)

标签:广度优先搜索

解法 时间复杂度 空间复杂度 执行用时
Ans 1 (Python) O ( X × Y ) O(X×Y) O(X×Y) O ( X × Y ) O(X×Y) O(X×Y) 6356ms (16.16%)
Ans 2 (Python)
Ans 3 (Python)

解法一:

class Solution:
    def minKnightMoves(self, x: int, y: int) -> int:
        ans = 0
        visited = {(0, 0)}
        queue = collections.deque([(0, 0)])
        while queue:
            for _ in range(len(queue)):
                x1, y1 = queue.popleft()
                if (x1, y1) == (x, y):
                    return ans
                for x2, y2 in [(x1 + 2, y1 - 1), (x1 + 2, y1 + 1), (x1 + 1, y1 + 2), (x1 + 1, y1 - 2), (x1 - 1, y1 + 2),
                               (x1 - 1, y1 - 2), (x1 - 2, y1 - 1), (x1 - 2, y1 + 1)]:
                    if (x2, y2) not in visited:
                        visited.add((x2, y2))
                        queue.append((x2, y2))

            ans += 1