if-else循环生成邻接矩阵结果异常,请求技术排查
邻接矩阵填充异常?排查思路与正确实现示例
Hey there! Sorry to hear your adjacency matrix code isn't outputting the expected result. Let's start by clarifying the expected matrix structure based on your description (assuming vertices are numbered 1 to 4):
# 1-based顶点对应的邻接矩阵 [ [0, 1, 0, 0], # 顶点1仅与顶点2相邻 [1, 0, 1, 0], # 顶点2与1、3相邻 [0, 1, 0, 1], # 顶点3与2、4相邻 [0, 0, 1, 0] # 顶点4仅与3相邻 ]
常见错误排查点
Here are the most common issues that lead to unexpected adjacency matrix results:
- Index mismatch: If your code uses 0-based indexing but you're thinking in 1-based vertex numbers, the connections will be shifted incorrectly.
- One-way assignment: For undirected graphs (which your description implies), you need to set both
matrix[u][v] = 1andmatrix[v][u] = 1. Forgetting the reverse assignment will create an asymmetric matrix. - Initialization errors: Failing to initialize the matrix with all 0s, or creating a matrix with the wrong dimensions (e.g., 3x4 instead of 4x4).
- Loop boundary mistakes: Off-by-one errors in loops that iterate over vertices (e.g., stopping at index 3 instead of 4 when working with 4 vertices).
正确实现示例
Here's a straightforward Python implementation that produces your expected matrix:
def build_adjacency_matrix(num_vertices, edges): # Initialize a num_vertices x num_vertices matrix filled with 0s adj_matrix = [[0] * num_vertices for _ in range(num_vertices)] for u, v in edges: # Convert 1-based vertex numbers to 0-based indices (adjust if you use 1-based indices) u_idx = u - 1 v_idx = v - 1 # Set both directions for undirected graph adj_matrix[u_idx][v_idx] = 1 adj_matrix[v_idx][u_idx] = 1 return adj_matrix # Define the edges from your description expected_edges = [(1, 2), (2, 3), (3, 4)] result_matrix = build_adjacency_matrix(4, expected_edges) # Print the result to verify for row in result_matrix: print(row)
Running this code will output exactly the matrix you expected:
[0, 1, 0, 0] [1, 0, 1, 0] [0, 1, 0, 1] [0, 0, 1, 0]
If your code still isn't working after checking these points, please share your actual code snippet—this will help pinpoint exactly where the issue is!
内容的提问来源于stack exchange,提问作者user8003788
相关产品推荐
相关产品推荐

