萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 解迷宮圖片三法:BFS、A* 與並查集視覺化

專案概覽

  • 輸入:迷宮圖片 (白色通道、黑色牆壁)
  • 輸出:解路徑動畫 GIF、標記連通區域
  • 演算法:BFS (廣度優先)、A* (啟發式)、Union-Find (連通區域標記)
  • 依賴:Pillow (PIL)、queue、標準庫
  • 原始碼:GitHub

BFS 解路徑

A* 解路徑 (搜尋節點較少)

並查集連通區域標記

核心程式碼結構

# -*- coding: utf-8 -*-
from PIL import Image
import Queue
import time

# 參數
imageName = "p.png"
ext = "png"
saveName = "{0:05d}.{1}"

# 載入並二值化
im = Image.open(imageName).convert("RGB")
pix = im.load()
w, h = im.size
half = 128
white = (255,255,255)
black = (0,0,0)

def binarize():
    for x in range(w):
        for y in range(h):
            r,g,b = pix[x,y]
            pix[x,y] = white if (r>half and g>half and b>half) else black

# 起點/終點 (依圖片調整)
start = (400, 984)
end   = (398, 25)

# ========== BFS ==========
def neighbors(p):
    x,y = p
    return [(x,y+1),(x+1,y),(x,y-1),(x-1,y)]

def in_bounds(p):
    x,y = p
    return 0 <= x < w and 0 <= y < h

def is_white(p):
    return pix[p] == white

def bfs(start, end):
    q = [[start]]
    visited = set([start])
    while q:
        path = q.pop(0)
        cur = path[-1]
        if cur == end:
            return path
        for nxt in neighbors(cur):
            if in_bounds(nxt) and is_white(nxt) and nxt not in visited:
                visited.add(nxt)
                q.append(path + [nxt])
    return None

# ========== A* ==========
import heapq
def heuristic(a, b):
    return abs(a[0]-b[0]) + abs(a[1]-b[1])  # 曼哈頓距離

def astar(start, end):
    open_set = [(heuristic(start, end), 0, start, [start])]
    g_score = {start: 0}
    while open_set:
        f, g, cur, path = heapq.heappop(open_set)
        if cur == end:
            return path
        for nxt in neighbors(cur):
            if not (in_bounds(nxt) and is_white(nxt)): continue
            tentative_g = g + 1
            if tentative_g < g_score.get(nxt, float('inf')):
                g_score[nxt] = tentative_g
                heapq.heappush(open_set, (tentative_g + heuristic(nxt, end), tentative_g, nxt, path + [nxt]))
    return None

# ========== 並查集 (連通區域) ==========
parent = list(range(w * h))
def find(x):
    while parent[x] != x:
        parent[x] = parent[parent[x]]
        x = parent[x]
    return x
def union(a, b):
    ra, rb = find(a), find(b)
    if ra != rb: parent[rb] = ra

def label_components():
    for x in range(w):
        for y in range(h):
            if is_white((x,y)):
                idx = y * w + x
                for nx, ny in neighbors((x,y)):
                    if in_bounds((nx,ny)) and is_white((nx,ny)):
                        union(idx, ny * w + nx)
    # 著色各連通域
    colors = [(255,0,0),(0,255,0),(0,0,255),(255,255,0),(0,223,248),(223,8,248),(255,2,146)]
    for x in range(w):
        for y in range(h):
            if is_white((x,y)):
                root = find(y * w + x)
                pix[x,y] = colors[root % len(colors)]

# ========== 主流程 ==========
binarize()

# BFS 動畫
path = bfs(start, end)
for i, pt in enumerate(path):
    pix[pt] = (255,0,0)  # 紅色路徑
    im.save(saveName.format(i, ext))

# A* 動畫 (同理)

# 並查集著色
label_components()
im.save("components.png")

# 產生 GIF
# 命令列: convert -delay 10 -loop 0 *.png maze.gif

效能比較 (該迷宮)

演算法搜尋節點數耗時特點
BFS較多較快無啟發式、優先佇列開銷小
A*少約 60%稍慢PriorityQueue 開銷抵銷搜尋減少量
Union-FindN/A極快近似 O(α(n)),適合連通域標記

小技巧:ImageMagick 產生 GIF

convert -delay 10 -loop 0 *.png maze.gif

極其方便,強烈推薦。

copyright © 萬盛學電腦網 all rights reserved