【发布时间】:2015-01-09 19:54:43
【问题描述】:
我写了一个程序的一部分,但找不到如何继续。这是我的作业,我已经做了十天了,我的时间即将到期。 我的程序要求: a) 获取 N 作为关键字的输入。 b) 生成 1 到 N*N 之间的随机整数 c) 用这些整数填充矩阵 我已经做到了,但我无法获得更多。
更多的是=>贪婪的方法 例如用户输入 3 作为输入。 和程序返回矩阵
1 2 6
4 8 5
3 9 7
最短路径是 1,2,6,5,7。 另一个示例用户输入 4 作为输入和程序返回矩阵,如
14 11 6 8
15 3 16 1
10 4 2 5
12 9 7 13
最短路径可以是14,11,3,4,2,5,13,
路径中不允许跨步。
我的代码如下。
import java.util.*;
public class Challenge1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a value for the matrix size.");
int length = input.nextInt();
int[][] x = randomMatrix(length);
for (int i = 0; i < x.length; i++) {
for (int j = 0; j < x[i].length; j++) {
System.out.print(x[i][j] + " ");
}
System.out.println();
}
}
public static int[][] randomMatrix(int n) {
Random r = new Random();
int[][] matrix = new int[n][n];
boolean[] trying = new boolean[n * n];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = r.nextInt(n * n) + 1;
if (trying[matrix[i][j] - 1] == false)
trying[matrix[i][j] - 1] = true;
else {
while (trying[matrix[i][j] - 1] == true) {
matrix[i][j] = r.nextInt(n * n) + 1;
}
trying[matrix[i][j] - 1] = true;
}
}
}
return matrix;
}
}
【问题讨论】:
-
这些数字对寻找最短路径有任何意义吗?澄清一下,我不知道您所说的
The more is =>Number of neighbor will check and will continue with the smallest.是什么意思,这简直难以理解。 -
该程序将检查邻居的数量,并继续使用最小的。
-
我认为路径是从左上角开始,在右下角结束;它的成本将是路径中条目的总和。
-
@ZpCikTi 我怀疑贪婪的方法会产生全局最优。
-
哦,好吧,前面的示例(编辑之前)只是沿着一条路径的边缘走,这条路径肯定没有最小的成本。