提出詳細
ソースコード
def dequeue(queue, top):
out = queue[0]
queue = queue[1:] + [[0, 0, 0]]
return out, queue, top - 1
def enqueue(queue, pos, times, top):
queue[top][0], queue[top][1], queue[top][2] = pos[0], pos[1], times
return queue, top + 1
t = int(input())
answer = []
for loop in range(t):
W, H = map(int, input().split())
n = [[0 for j in range(W)] for i in range(H)] # H, W
queue = [[0, 0, 0] for i in range(100000)]
for i in range(H):
n[i] = list(map(int, input().split()))
for j in range(W):
if n[i][j] == 1:
queue[0] = [i, j, 0]
# ここから幅優先探索
ans_tmp, bfs = 0, True
course = [[0, 1], [0, -1], [1, 0], [-1, 0]]
tonext = [0, 0]
top, tmp, postop = 1, False, 1
position = [[-1, -1] for i in range(H * W + 1)]
position[0] = queue[0][:2]
while(bfs):
if top == 0:
ans_tmp = 0
break
now, queue, top = dequeue(queue, top)
ans_tmp = now[2] + 1
for i in range(4):
tonext[0] = now[0] + course[i][0]
tonext[1] = now[1] + course[i][1]
if tonext[0] < 0 or tonext[0] >= H or tonext[1] < 0 or tonext[1] >= W:
continue
tmp = False
for j in position:
if j == tonext:
tmp = True
break
if tmp:
continue
if n[tonext[0]][tonext[1]] == 2:
bfs = False
break
elif n[tonext[0]][tonext[1]] == 0:
queue, top = enqueue(queue, tonext, ans_tmp, top)
position[postop][0], position[postop][1] = tonext[0], tonext[1]
postop += 1
answer.append(ans_tmp)
for loop in range(t):
print("Case #{}:".format(loop + 1))
print(answer[loop])
提出情報
提出出力結果
テストケース情報