CCF Python題解(60分)201604-4 遊戲
阿新 • • 發佈:2018-11-13
CCF Python題解(60分)201604-4 遊戲
# 最短路徑 廣義優先搜尋 BFS
# 所以有時候需要在一些地方踱步,等過了這段時間再前行,就不能簡單地限制為進入過的格不能再進入。
from collections import deque
visited = [[[0 for k in range(301)] for i in range(101)] for j in range(101)]
n, m, t = map(int, input().split())
direct = [[-1, 0], [1, 0], [0, -1], [0, 1]]
for i in range(t) :
r, c, a, b = map(int, input().split())
for j in range(a, b + 1):
visited[r][c][j] = 1
def bfs(x, y):
q = deque()
q.append([1, 1, 0])
while len(q) != 0:
front = q.popleft()
if front[0] == x and front[1] == y:
return front[2]
for k in range (4):
row = front[0] + direct[k][0]
col = front[1] + direct[k][1]
level = front[2] + 1
if row < 1 or row > n or col < 1 or col > m or visited[row][col][level]:
continue
visited[row][col][level] = 1
q.append( [row, col, level])
print(bfs(n, m))