如何将邻接矩阵的用户输入方式改为程序硬编码实现?
问题描述
现有一段Java代码,通过Scanner获取用户输入的顶点数和带权邻接矩阵,并对矩阵进行初始化处理(对角线设为0,非对角线0设为Integer.MAX_VALUE),原代码如下:
try { System.out.println("Enter the number of vertices"); number_of_vertices = scan.nextInt(); adjacency_matrix = new int[number_of_vertices + 1][number_of_vertices + 1]; System.out.println("Enter the Weighted Matrix for the graph"); for (int i = 1; i <= number_of_vertices; i++) { for (int j = 1; j <= number_of_vertices; j++) { adjacency_matrix[i][j] = scan.nextInt(); if (i == j) { adjacency_matrix[i][j] = 0; continue; } if (adjacency_matrix[i][j] == 0) { adjacency_matrix[i][j] = Integer.MAX_VALUE; } } }
用户输入示例如下:
Enter the number of vertices 5 Enter the Weighted Matrix for the graph 0 9 6 5 3 0 0 0 0 0 0 2 0 4 0 0 0 0 0 0 0 0 0 0 0
现在需要将上述通过用户输入邻接矩阵的方式改为直接在程序中硬编码实现,该如何操作?
解决方案
要实现硬编码,只需替换原有的Scanner输入逻辑,直接在代码中定义顶点数和原始矩阵数据,再保留原有的初始化规则即可,具体实现如下:
修改后的完整代码
// 直接硬编码顶点数(对应示例输入的5) int number_of_vertices = 5; int[][] adjacency_matrix = new int[number_of_vertices + 1][number_of_vertices + 1]; // 硬编码原始邻接矩阵数据,索引0留空以适配原代码的1-based遍历逻辑 int[][] rawMatrix = { {0, 0, 0, 0, 0, 0}, {0, 0, 9, 6, 5, 3}, {0, 0, 0, 0, 0, 0}, {0, 0, 2, 0, 4, 0}, {0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0} }; // 保留原有的矩阵初始化处理规则 for (int i = 1; i <= number_of_vertices; i++) { for (int j = 1; j <= number_of_vertices; j++) { adjacency_matrix[i][j] = rawMatrix[i][j]; // 对角线强制设为0 if (i == j) { adjacency_matrix[i][j] = 0; continue; } // 非对角线的0替换为Integer.MAX_VALUE if (adjacency_matrix[i][j] == 0) { adjacency_matrix[i][j] = Integer.MAX_VALUE; } } }
关键说明
- 硬编码的
rawMatrix保留了索引0的空数组,和原代码的1-based遍历逻辑对齐,无需修改循环范围。 - 原有的矩阵初始化规则完全保留,确保处理后的矩阵和用户输入得到的结果一致。
- 移除了
Scanner相关代码和控制台输入提示,程序启动后直接完成矩阵初始化。
内容的提问来源于stack exchange,提问作者Akhil 546u
相关产品推荐
相关产品推荐

