置頂

我的 VPython 教學文件 (HackMD 版本)

VPython 教學文件目錄 安裝及測試 基本語法 等速度直線運動 自由落下 終端速度 水平抛射 使用For迴圈計算水平抛射資料 斜向抛射 圓周運動 簡諧運動 單擺 木塊彈簧系統分離 重力及簡諧 行星運動 相疊木塊 雙重簡諧運動 一維彈性碰撞 ...

熱門文章

2026年11月4日 星期三

ZeroJudge 解題筆記:t167.機器人迷宮

作者:王一哲
日期:2026年11月4日


ZeroJudge 題目連結:t167.機器人迷宮

解題想法


每組測資第一列為兩個整數 $h ~(1 \leq h \leq 1000), w ~(1 \leq w \leq 1000)$,代表地圖的尺寸為 $h \times w$;接下來第 $h$ 列每有一個長度為 $w$ 的字串,字串中只有代表空地的 . 及代表牆壁的 #。機器人從地圖左上角 $(0, 0)$ 出發,終點為地圖右下角 $(h-1, w-1)$,保證起點、終點皆為空地。求走到終點的最少步數,如果無法走到終點則印出 $-1$。

這題是標準的 BFS。 我另外開一個 $h \times w$ 的陣列 $step$,記錄走到某個位置的步數,預設值皆為 $-1$,代表沒有走到,另外設定 $step[0][0] = 0$。待走訪佇列 $que$ 先放入起點 $(0, 0)$。用 while 跑 BFS,從 $que$ 最前面取出目前走訪的位置 $(r, c)$,如果走到終點就中止迴圈;反之,用四方位檢查找下一格 $(nr, nc)$ 並更新 $step[nr][nc]$。走完 BFS 之後印出 $step[h-1][w-1]$。

Python 程式碼


使用時間約為 0.9 s,記憶體約為 48.2 MB,通過測試。
def solve():
    import sys
    from collections import deque
    
    result = []
    data = sys.stdin.read().split()
    ptr = 0
    while ptr < len(data):
        h = int(data[ptr])
        w = int(data[ptr + 1])
        ptr += 2
        grid = data[ptr : ptr + h]
        ptr += h
        step = [[-1] * w for _ in range(h)]
        step[0][0] = 0
        que = deque([(0, 0)])
        while que:
            r, c = que.popleft()
            if r == h - 1 and c == w - 1:
                break
            for dr, dc in ((0, 1), (1, 0), (0, -1), (-1, 0)):
                nr, nc = r + dr, c + dc
                if 0 <= nr < h and 0 <= nc < w and grid[nr][nc] == '.' and step[nr][nc] == -1:
                    step[nr][nc] = step[r][c] + 1
                    que.append((nr, nc))
        result.append(f"{step[h - 1][w - 1]:d}\n")
    sys.stdout.write("".join(result))

if __name__ == "__main__":
    solve()


使用時間約為 2.1 s,記憶體約為 48.2 MB,通過測試。
from collections import deque

while True:
    try:
        h, w = map(int, input().split())
    except EOFError:
        break
    
    grid = [input() for _ in range(h)]
    step = [[-1] * w for _ in range(h)]
    step[0][0] = 0
    que = deque([(0, 0)])
    while que:
        r, c = que.popleft()
        if r == h - 1 and c == w - 1:
            break
        for dr, dc in ((0, 1), (1, 0), (0, -1), (-1, 0)):
            nr, nc = r + dr, c + dc
            if 0 <= nr < h and 0 <= nc < w and grid[nr][nc] == '.' and step[nr][nc] == -1:
                step[nr][nc] = step[r][c] + 1
                que.append((nr, nc))
    print(step[h - 1][w - 1])


C++ 程式碼


使用時間約為 28 ms,記憶體約為 8.6 MB,通過測試。
#include <iostream>
#include <vector>
#include <queue>
#include <utility>
using namespace std;

int main() {
    ios::sync_with_stdio(0); cin.tie(0);
    int h, w;
    while(cin >> h >> w) {
        vector<string> grid (h);
        for(int i = 0; i < h; i++) {
            cin >> grid[i];
        }
        
        vector<vector<int>> step (h, vector<int> (w, -1));
        step[0][0] = 0;
        queue<pair<int, int>> que;
        que.push({0, 0});
        int dr[4] = {0, 1, 0, -1}, dc[4] = {1, 0, -1, 0};
        while(!que.empty()) {
            int r = que.front().first, c = que.front().second;
            que.pop();
            if (r == h - 1 && c == w - 1) break;
            for(int i = 0; i < 4; i++) {
                int nr = r + dr[i], nc = c + dc[i];
                if (nr >= 0 && nr < h && nc >= 0 && nc < w && grid[nr][nc] == '.' && step[nr][nc] == -1) {
                    step[nr][nc] = step[r][c] + 1;
                    que.push({nr, nc});
                }
            }
        }
        cout << step[h - 1][w - 1] << "\n";
    }
    return 0;
}


沒有留言:

張貼留言