2024年10月24日 星期四

迷宮導航II

 迷宮導航示例。這個版本將實際運行檢查左、前、右的路徑,並包含轉向和移動的邏輯:

完整的 Python 實作

# 定義迷宮 (0 表示路,1 表示牆)
maze = [
    [1, 1, 1, 1, 1, 1, 1, 1],
    [1, 0, 0, 1, 0, 0, 0, 1],
    [1, 1, 0, 1, 0, 1, 0, 1],
    [1, 0, 0, 0, 0, 1, 0, 1],
    [1, 1, 1, 1, 1, 1, 1, 1]
]

# 起點和終點
row, col = 1, 1
goal_row, goal_col = 3, 6

# 方向順時針依次為: 上, 右, 下, 左
directions = [(-1, 0), (0, 1), (1, 0), (0, -1)]
current_direction = 1  # 初始方向設為「右」

# 判斷是否尚未抵達終點
def not_done():
    return (row, col) != (goal_row, goal_col)

# 檢查左邊是否有路可走
def is_path_left():
    # 計算左轉後的方向索引
    left_direction = (current_direction - 1) % 4
    offset_row, offset_col = directions[left_direction]
    return maze[row + offset_row][col + offset_col] == 0

# 檢查前方是否有路可走
def is_path_forward():
    offset_row, offset_col = directions[current_direction]
    return maze[row + offset_row][col + offset_col] == 0

# 檢查右邊是否有路可走
def is_path_right():
    # 計算右轉後的方向索引
    right_direction = (current_direction + 1) % 4
    offset_row, offset_col = directions[right_direction]
    return maze[row + offset_row][col + offset_col] == 0

# 向左轉
def turn_left():
    global current_direction
    current_direction = (current_direction - 1) % 4

# 向右轉
def turn_right():
    global current_direction
    current_direction = (current_direction + 1) % 4

# 向前移動
def move_forward():
    global row, col
    offset_row, offset_col = directions[current_direction]
    row += offset_row
    col += offset_col
    maze[row][col] = 2  # 標記已走過的路徑
    print(f"Moved to ({row}, {col})")

# 將起點標記為已訪問
maze[row][col] = 2

# 主導航迴圈
while not_done():
    if is_path_left():
        turn_left()
        move_forward()
    else:
        if is_path_forward():
            move_forward()
        else:
            if is_path_right():
                turn_right()
                move_forward()
            else:
                turn_right()

print("Reached the goal!")

程式說明

  1. 迷宮結構

    • maze 是一個 5x8 的矩陣,其中 1 代表牆壁,0 代表可以通行的路。
    • 起點設在 (1, 1),終點設在 (3, 6)
  2. 方向控制

    • 使用 directions 列表來管理四個方向:上、右、下、左,初始設定為「右」。
    • 通過 turn_left() 和 turn_right() 來調整方向索引。
  3. 導航邏輯

    • 優先嘗試向左轉,如果左邊有路,則左轉並前進。
    • 如果左邊無法通行,則檢查前方;如果前方有路,則直接前進。
    • 如果左邊和前方都不能通行,則檢查右邊;如果右邊有路,則右轉並前進。
    • 若三個方向都無法通行,則右轉,可能準備嘗試新的路線。
  4. 走過的路徑標記

    • 當前程式會將已經走過的路徑標記為 2,避免重複行走相同路徑。

執行結果

執行這段程式後,導航過程會輸出每一步的位置:

Moved to (1, 2)
Moved to (2, 2)
Moved to (3, 2)
Moved to (3, 3)
Moved to (3, 4)
Moved to (2, 4)
Moved to (1, 4)
Moved to (1, 5)
Moved to (1, 6)
Moved to (2, 6)
Moved to (3, 6)
Reached the goal!

結論

這段完整的程式展示了如何從起點 (1,1) 導航到終點 (3,6),並且通過檢查左、前、右來決定行進方向。每一步都根據周圍的情況調整,直到成功抵達目標位置。

沒有留言:

張貼留言