AcWing BFS相关问题 188. 武士风度的牛


import sys
sys.stdin = open('data.txt', 'r')

'''
BFS层次遍历,求最短路径长度
'''


from collections import deque

n, m = map(int, input().split())
si, sj = -1, -1
ei, ej = -1, -1


grid = []
for i in range(m):
    s = input()
    grid.append( [ch for ch in s] )
    try:
        idx = s.index('K')
        si, sj = i, idx
    except:
        pass


    try:
        idx = s.index('H')
        ei, ej = i, idx
    except:
        pass

que = deque()
que.append((si, sj))
visited = {(si, sj)}

step = 0
ans = 0
flag = False
while len(que) > 0:

    nodes_num = len(que)
    for _ in range(nodes_num):
        i, j = que.popleft()

        for ii, jj in [ [i-1, j-2], [i-1, j+2], [i+1, j-2], [i+1, j+2], [i-2, j-1], [i-2, j+1], [i+2, j-1], [i+2, j+1] ]:
            if ii >= 0 and ii < m and jj >

你可能感兴趣的:(AcWing,BFS相关问题,算法)