为什么此BFS队列不返回None?

时间:2018-09-20 16:48:05

标签: python-3.x shortest-path breadth-first-search

我目前正在尝试称为Castle on the Grid的Hackerrank问题, 在其中,我已经在Python 3中实现了BFS,如下所示:

#!/bin/python3

import math
import os
import random
import re
import sys
from collections import deque

def minimumMoves(grid, startX, startY, goalX, goalY):
    n = len(grid)
    queue = deque()
    queue.append((startY,startX))
    goal = (goalY,goalX)
    turnsMatrix = [[0]*n]*n

    while queue:
        current = queue.popleft()
        (Y0, X0) = current
        print(current)
        d = turnsMatrix[Y0][X0]

        if current == goal:
            return(d)

        for X in range(X0-1,-1,-1):
            if grid[Y0][X] == 'X':
                break
            elif turnsMatrix[Y0][X] == 0:
                turnsMatrix[Y0][X] = d + 1
                queue.append((Y0,X))

        for Y in range(Y0-1,-1,-1):
            if grid[Y][X0] == 'X':
                break
            elif turnsMatrix[Y][X0] == 0:
                turnsMatrix[Y][X0] = d + 1
                queue.append((Y,X0))

        for X in range(X0+1,n):
            if grid[Y0][X] == 'X':
                break
            elif turnsMatrix[Y0][X] == 0:
                turnsMatrix[Y0][X] = d + 1
                queue.append((Y0,X))

        for Y in range(Y0+1,n):
            if grid[Y][X0] == 'X':
                break
            elif turnsMatrix[Y][X0] == 0:
                turnsMatrix[Y][X0] = d + 1
                queue.append((Y,X0))

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')
    n = int(input())
    grid = []

    for _ in range(n):
        grid_item = input()
        grid.append(grid_item)

    startXStartY = input().split()
    startX = int(startXStartY[0])
    startY = int(startXStartY[1])
    goalX = int(startXStartY[2])
    goalY = int(startXStartY[3])
    result = minimumMoves(grid, startX, startY, goalX, goalY)
    fptr.write(str(result) + '\n')
    fptr.close()

但是,尽管只有一个return语句应该返回int,但是我的代码还是返回了None。我知道deque最终会变空并返回None,但是我很难弄清为什么事情不再追加到队列中。

对于测试用例

3
.X.
.X.
...
0 0 0 2

我注意到会发生什么:

1)城堡向右移动并在X处中断。

2)城堡向下移动一个格,并且匝数矩阵变为

[[1, 0, 0], [1, 0, 0], [1, 0, 0]].

3)queue变成deque([(1, 0)])

4)返回无。

这是怎么回事?我一直盯着我的代码好几天了,我快要疯了……请帮助,谢谢!

0 个答案:

没有答案