【问题标题】:Problems finding the shortest path on the matrix在矩阵上找到最短路径的问题
【发布时间】: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 =&gt;Number of neighbor will check and will continue with the smallest. 是什么意思,这简直难以理解。
  • 该程序将检查邻居的数量,并继续使用最小的。
  • 我认为路径是从左上角开始,在右下角结束;它的成本将是路径中条目的总和。
  • @ZpCikTi 我怀疑贪婪的方法会产生全局最优。
  • 哦,好吧,前面的示例(编辑之前)只是沿着一条路径的边缘走,这条路径肯定没有最小的成本。

标签: java matrix


【解决方案1】:

这是我在评论中提到的解决方案的一些 python 式伪代码。让shortestPath 是一个最初为空的列表,shortestPathCost 是找到的最短路径的权重之和。最初它的值为+infinity。两者都是全局可见的。

 Procedure exhaustiveSearch (currentCost, currentPath, endNode):
      currentNode = currentPath.last
      if currentNode == endNode and currentCost < shortestPathCost:
           shortestPath = currentPath
           shortestPathCost = currentCost
           return

      for each neighbouringNode of currentNode not in currentPath:
           exhaustiveSearch (currentCost + neighbouringNode.cost, 
                             currentPath + neighbouringNode,
                             endNode)

差不多就是这样。参数按值复制。如果你这样调用它:

 exhaustiveSearch(0, [firstNode], endNode);

shortestPathshortestPathCost 将保留网格中最短的路径之一。显然,该解决方案比Java 本身要高一些,但应该很容易实现。

【讨论】:

  • 我认为你在最后添加了两次“neighboringNode”。编辑:没关系,你修好了。
  • 是的,我更改了一些参数,但没有更改调用。谢谢指正。
  • 非常感谢。我会努力制作的。
猜你喜欢
  • 2013-12-15
  • 1970-01-01
  • 2022-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-13
相关资源
最近更新 更多