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 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
| import matplotlib.pyplot as plt import numpy as np from matplotlib.animation import FuncAnimation
class AlgorithmVisualizer: """算法可视化工具""" @staticmethod def visualize_sorting(arr, algorithm='bubble'): """排序算法可视化""" fig, ax = plt.subplots() bars = ax.bar(range(len(arr)), arr) def bubble_sort_steps(arr): steps = [] n = len(arr) arr_copy = arr.copy() for i in range(n): for j in range(0, n - i - 1): if arr_copy[j] > arr_copy[j + 1]: arr_copy[j], arr_copy[j + 1] = arr_copy[j + 1], arr_copy[j] steps.append((arr_copy.copy(), j, j + 1)) return steps steps = bubble_sort_steps(arr) def animate(frame): if frame < len(steps): arr_state, idx1, idx2 = steps[frame] for i, (bar, height) in enumerate(zip(bars, arr_state)): bar.set_height(height) if i in [idx1, idx2]: bar.set_color('red') else: bar.set_color('blue') anim = FuncAnimation(fig, animate, frames=len(steps), interval=200, repeat=False) plt.show() return anim @staticmethod def visualize_pathfinding(grid, start, end, algorithm='bfs'): """路径查找算法可视化""" from collections import deque def bfs_pathfinding(grid, start, end): rows, cols = len(grid), len(grid[0]) queue = deque([(start, [start])]) visited = {start} steps = [] directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] while queue: (x, y), path = queue.popleft() steps.append((visited.copy(), path)) if (x, y) == end: return steps, path for dx, dy in directions: nx, ny = x + dx, y + dy if (0 <= nx < rows and 0 <= ny < cols and grid[nx][ny] == 0 and (nx, ny) not in visited): visited.add((nx, ny)) queue.append(((nx, ny), path + [(nx, ny)])) return steps, [] steps, final_path = bfs_pathfinding(grid, start, end) fig, ax = plt.subplots() im = ax.imshow(grid, cmap='binary') def animate(frame): if frame < len(steps): visited, current_path = steps[frame] display_grid = np.array(grid, dtype=float) for x, y in visited: if (x, y) not in [start, end]: display_grid[x][y] = 0.5 for x, y in current_path: if (x, y) not in [start, end]: display_grid[x][y] = 0.3 im.set_array(display_grid) anim = FuncAnimation(fig, animate, frames=len(steps), interval=100, repeat=False) plt.show() return anim
|