1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
from collections import deque
dx = [0,0,1,-1] # 右左下上
dy = [1,-1,0,0]
def main():
h, w = map(int, input().split())
s = [input() for _ in range(h)]
sx, sy, gx, gy = -1, -1, -1, -1
for i in range(h):
row = s[i]
for j in range(w):
if row[j] == 'S':
sx, sy = i, j
elif row[j] == 'G':
gx, gy = i, j
# visited[i][j]: 使用位掩码表示方向,0为水平,1为垂直
visited = [0] * (h * w)
q = deque()
# (x, y, steps, last_direction)
q.append((sx, sy, 0, -1))
visited[sx * w + sy] |= 0b11 # 标记水平和垂直方向已访问
while q:
tx, ty, step, last_dir = q.popleft()
if tx == gx and ty == gy:
print(step)
return
for i in range(4):
nx = tx + dx[i]
ny = ty + dy[i]
if 0 <= nx < h and 0 <= ny < w and s[nx][ny] != '#':
curr_dir = 0 if i < 2 else 1
if last_dir == -1 or curr_dir != last_dir:
idx = nx * w + ny
if not (visited[idx] & (1 << curr_dir)):
visited[idx] |= (1 << curr_dir)
q.append((nx, ny, step + 1, curr_dir))
print(-1)
if __name__ == "__main__":
main()
|