如何基于坐标列表创建管道网格并检测源到目标的连接有效性?
管道网格连通性检测:网格构建与遍历方案
网格构建(基于Pandas数据)
- 把Pandas读取的坐标数据转换成二维列表网格是最直接的方式,方便后续遍历和访问:
import pandas as pd # 读取文本文件,假设列名是x, y, pipe_char df = pd.read_csv("pipe_grid.txt") # 确定网格边界(坐标从0开始的情况) max_x, max_y = df["x"].max(), df["y"].max() # 初始化空网格 grid = [[None for _ in range(max_x + 1)] for _ in range(max_y + 1)] # 填充网格数据 for _, row in df.iterrows(): x, y, char = row["x"], row["y"], row["pipe_char"] grid[y][x] = char - 构建完成后,可通过
grid[y][x]直接访问对应坐标的管道字符,遍历逻辑清晰直观。
网格遍历与连通性检测(无需额外库)
不需要专门的网格处理库,用Python内置结构+DFS/BFS算法就能解决连通性问题,这里给出BFS实现示例(适配常见管道类型):
from collections import deque # 定义每种管道允许的连通方向(dy, dx),根据你的管道规则调整 pipe_dirs = { "|": [(-1, 0), (1, 0)], # 上下连通 "-": [(0, -1), (0, 1)], # 左右连通 "L": [(-1, 0), (0, 1)], # 上→右 "J": [(-1, 0), (0, -1)], # 上→左 "7": [(1, 0), (0, -1)], # 下→左 "F": [(1, 0), (0, 1)] # 下→右 } def check_connection(grid, start_point, end_point): max_y, max_x = len(grid), len(grid[0]) if grid else 0 visited = set() queue = deque([start_point]) visited.add(start_point) while queue: y, x = queue.popleft() if (y, x) == end_point: return True current_pipe = grid[y][x] if current_pipe not in pipe_dirs: continue # 遍历当前管道的所有连通方向 for dy, dx in pipe_dirs[current_pipe]: ny, nx = y + dy, x + dx # 检查边界合法性 if 0 <= ny < max_y and 0 <= nx < max_x: neighbor_pipe = grid[ny][nx] # 验证相邻管道是否能反向连通(避免单向无效连接) if neighbor_pipe in pipe_dirs and (-dy, -dx) in pipe_dirs[neighbor_pipe]: if (ny, nx) not in visited: visited.add((ny, nx)) queue.append((ny, nx)) return False
实用提示
- 确认坐标规则:如果你的网格y轴向下为正,需调整网格索引的对应关系;
- 测试阶段先打印
grid,验证每个坐标的管道字符是否正确填充; - 若需更高效的数值运算,可将二维列表转为
numpy数组,但纯Python实现完全满足这类问题需求。
内容的提问来源于stack exchange,提问作者Boltu
相关产品推荐
相关产品推荐

