h, w = map(int,input().split()) s = [input() for _ in range(h)] a,b,c,d = map(lambda x:…
Private research annotation
Sign in to add a private research label or note.
- User
h, w = map(int,input().split()) s = [input() for _ in range(h)] a,b,c,d = map(lambda x: int(x)-1,input().split())
from collections import deque inf = cost = [[inf]*w for _ in range(h)] DIR_4 = {(0,1),(0,-1),(1,0),(-1,0)} def bfs01(i, j): que = deque() que.append((i, j)) cost[i][j] = 0
codewhile que: cx, cy = que.popleft() for dx,dy in DIR_4: n_cost = cost[cx][cy] nx = cx + dx <REDACTED> = cy + dy if not(0<=nx<h and 0<=ny<w): continue # 1こすすんで壁 if s[nx][ny] == "#": n_cost += 1 if cost[nx][ny] > n_cost: cost[nx][ny] = n_cost que.append((nx,<REDACTED>)) # 2個進む遷移 n_cost = cost[cx][cy] nx2 = cx + 2*dx ny2 = cy + 2*dy if not(0<=nx2<h and 0<=ny2<w): continue # s[nx][ny]が"#"でs[nx2][ny2]が"." -> cost++ # s[nx2][ny2]が"."でs[nx2][ny2]が"#" -> cost++ # s[nx][ny]とs[nx2][ny2]が"#" -> cost++ # s[nx][ny]とs[nx2][ny2]が"." -> cost+=0 if s[nx][ny] == "#" or s[nx2][ny2] == "#": n_cost += 1 if cost[nx2][ny2] > n_cost: cost[nx2][ny2] = n_cost que.append((nx2,ny2))bfs01(a, b)
print(cost[c][d])
でなぜか、TLEになってしまいます。ACはできているので方針は良さそうです。
- Assistant
TLE(Time Limit Exceeded)になる原因として、このコードでは以下の点がパフォーマンス上のボトルネックになっている可能性があります:
🔍 問題の本質:通常のdequeでは 0-1 BFS に最適でない
この問題のように「コストが 0 または 1」で遷移するグラフでは、0-1 BFSというテクニックを使うと高速に解けます。
✅ 修正案:0-1 BFS にする(appendleftを使う)
以下のように、コストが上がらない場合(n_costが増えない遷移)はappendleft、コストが増える遷移はappendにすることで、常に現在最小のコストから探索することができます。
修正済みのbfs01関数👇
────────────────────────────────────────────────────────────────────
pythonCopy codedef deque() que.append((i, j)) cost[i][j] = 0