矩阵坐标路径求和最大值问题求解及代码完善咨询
问题解答
初始矩阵代码正确性确认
你写的初始代码是正确的,它能准确读取输入的矩阵行数、每行元素,并将矩阵存储为二维整数列表,完全符合输入要求。
后续实现步骤
接下来可以按以下步骤完成剩余功能:
1. 读取并解析坐标对
最后一行输入是成对的R、C坐标,需要将其拆分为多个(R, C)元组:
coords = list(map(int, input().split())) # 两两分组生成坐标对 coordinate_pairs = [(coords[i], coords[i+1]) for i in range(0, len(coords), 2)]
2. 编写路径和计算函数
针对每个坐标对,按照规则计算路径累加和:
def compute_path_total(matrix, total_rows, r, c): # 确定起始行索引和起始列 if r > 0: row_idx = r - 1 # 1-based行号转0-based索引 start_col = 0 else: row_idx = total_rows + r # 负行号转0-based索引(如r=-4,总行数5则对应索引1) start_col = len(matrix[row_idx]) - 1 # 行末尾列索引 # 确定目标列索引(C的绝对值是1-based列号) target_col = abs(c) - 1 # 计算水平移动的和 horizontal_total = 0 # 根据起始列和目标列的位置确定遍历方向 if start_col <= target_col: for col in range(start_col, target_col + 1): horizontal_total += matrix[row_idx][col] else: for col in range(start_col, target_col - 1, -1): horizontal_total += matrix[row_idx][col] # 计算垂直移动的和(避免重复计算当前行的目标列) vertical_total = 0 if c > 0: # 向上移动,从当前行的上一行到第一行 for row in range(row_idx - 1, -1, -1): vertical_total += matrix[row][target_col] else: # 向下移动,从当前行的下一行到最后一行 for row in range(row_idx + 1, total_rows): vertical_total += matrix[row][target_col] return horizontal_total + vertical_total
3. 计算所有路径和并找出最大值
遍历所有坐标对,计算每个路径的和,记录最大值并输出:
max_total = -float('inf') for r, c in coordinate_pairs: current_total = compute_path_total(matrix, rows, r, c) if current_total > max_total: max_total = current_total print(max_total)
完整代码整合
将所有部分整合后的完整代码:
rows = int(input()) matrix = [] for _ in range(rows): row = list(map(int, input().split())) matrix.append(row) # 读取坐标对 coords = list(map(int, input().split())) coordinate_pairs = [(coords[i], coords[i+1]) for i in range(0, len(coords), 2)] def compute_path_total(matrix, total_rows, r, c): if r > 0: row_idx = r - 1 start_col = 0 else: row_idx = total_rows + r start_col = len(matrix[row_idx]) - 1 target_col = abs(c) - 1 horizontal_total = 0 if start_col <= target_col: for col in range(start_col, target_col + 1): horizontal_total += matrix[row_idx][col] else: for col in range(start_col, target_col - 1, -1): horizontal_total += matrix[row_idx][col] vertical_total = 0 if c > 0: for row in range(row_idx - 1, -1, -1): vertical_total += matrix[row][target_col] else: for row in range(row_idx + 1, total_rows): vertical_total += matrix[row][target_col] return horizontal_total + vertical_total max_total = -float('inf') for r, c in coordinate_pairs: current_total = compute_path_total(matrix, rows, r, c) if current_total > max_total: max_total = current_total print(max_total)
说明
- 代码中所有行、列坐标均按题目要求从1-based转换为Python的0-based索引
- 水平移动会累加从起点列到目标列的所有单元格(包含两端)
- 垂直移动不会重复计算当前行的目标列单元格(已在水平移动中累加)
- 初始最大值设为负无穷,确保能正确处理所有元素为负数的情况
内容的提问来源于stack exchange,提问作者Donko Tonev
相关产品推荐
相关产品推荐

