N, M = map(int, input().split(" ")) edges = [list(map(int, input().split(" "))) for _ inrange(M)]
if M == 1: print(edges[0][2]) exit()
# 對每個點DFS,紀錄最大的距離 adj = [[0]*(N+1) for _ inrange(N+1)] for edge in edges: X, Y, W = edge adj[X][Y] = W adj[Y][X] = W
visited = [Falsefor _ inrange(N+1)]
ans = 0 defdfs(v): cur = 0 visited[v] = True for j inrange(1, N+1): if adj[v][j] != 0andnot visited[j]: res = dfs(j) cur = max(cur, res+adj[v][j]) visited[v] = False return cur
for i inrange(1, N+1): ans = max(ans, dfs(i)) print(ans)
# 構建迷宮的矩陣,並在上下左右加上牆壁,以免出界 H , W = map(int, input().split(" ")) Maze = [list(f"#{input()}#") for _ inrange(H)] Maze = [["#"]*(W+2)] + Maze + [["#"]*(W+2)]
# 先找出起點、終點、以及所有的箭頭位置 start = goal = None arrows = [] for i inrange(1, H+1): for j inrange(1, W+1): if Maze[i][j] == "S": start = (i, j) elif Maze[i][j] == "G": goal = (i, j) elif Maze[i][j] in"<>^v": arrows.append((i, j)) # 再來處理箭頭 arrow_map = {"<":(0, -1), ">":(0, 1), "^":(-1, 0), "v":(1, 0)} for pi, pj in arrows: di, dj = arrow_map[Maze[pi][pj]] i, j = pi+di, pj+dj while Maze[i][j] notin"#<>^v": Maze[i][j] = "!"# 為了不影響其他箭頭的判定情況,先標記為"!" i, j = i+di, j+dj # 最後將地圖中的可走路徑標記為0,牆壁或可視為牆壁的符號標記為-1 # 這樣就可以用BFS來走迷宮了,且這個矩陣的元素代表路徑長度 for i inrange(H+2): for j inrange(W+2): if Maze[i][j] in"#!<>^v": Maze[i][j] = -1 else: Maze[i][j] = 0 # BFS from collections import deque queue = deque([start]) while queue: pi, pj = queue.popleft() if (pi, pj) == goal: # 找到終點就停止 break for di, dj in [(-1, 0), (1, 0), (0, -1), (0, 1)]: if Maze[pi+di][pj+dj] == 0: #檢查上下左右是否可走且未走過 Maze[pi+di][pj+dj] = Maze[pi][pj] + 1 queue.append((pi+di, pj+dj)) print(-1) if Maze[goal[0]][goal[1]] == 0elseprint(Maze[goal[0]][goal[1]])
寫在最後
Cover photo is created by @CC Lin, thanks for their work!
I did not find any copyright declaration on the author’s personal page regarding permission or prohibition of use. Because of this, I used Pixiv.Cat to proxy the cover image. I actually do not save that image.
If the content of the article infringes on your copyright, please contact me through email or leave a comment to let me know, and I will promptly remove the relevant content.