Python构建5高10宽网格图:移除对角线边的实现需求
Solution to Remove Diagonal Edges
The issue with your current code is that it’s iterating over all 8 possible adjacent directions (including diagonals). To keep only the cardinal directions (up, down, left, right), you just need to adjust the set of direction vectors you’re checking.
Corrected Code
Here’s the full modified construct_graph function:
from itertools import product def construct_graph(data): # Initialize all of the astar nodes nodes = [[ANode(x, y) for y in range(data['height'])] for x in range(data['width'])] graph = {} # Make a graph with child nodes (only cardinal directions) for x, y in product(range(data['width']), range(data['height'])): node = nodes[x][y] graph[node] = [] # Define only cardinal directions (no diagonals) directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] for dx, dy in directions: new_x = x + dx new_y = y + dy # Check if the new coordinates are within grid bounds if 0 <= new_x < data['width'] and 0 <= new_y < data['height']: neighbor_node = nodes[new_x][new_y] graph[node].append(neighbor_node) return graph
Key Changes Explained
- Direction Vectors: Instead of using all combinations of (-1,0,1) for both axes (which includes diagonals like (-1,-1)), we explicitly list only the four cardinal directions:
(-1, 0): Left(1, 0): Right(0, -1): Down (adjust this to(0,1)if your grid uses y-axis upward)(0, 1): Up
- Bounds Checking: We still verify that neighboring coordinates stay within the grid’s width and height to avoid index errors.
This adjustment ensures each node only has edges to its immediate up, down, left, and right neighbors, removing all diagonal connections entirely.
内容的提问来源于stack exchange,提问作者evilGenious
相关产品推荐
相关产品推荐

