繁体   English   中英

在矩阵上找到最短路径的问题

[英]Problems finding the shortest path on the matrix

我写了一部分程序,但找不到如何继续。这是我的作业,并且已经工作了十天,我的时间即将到期。 我的程序要求: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;
    }

}

这是我在评论中提到的解决方案的一些python-ish伪代码。 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本身更高一级,但实现起来应该是直截了当的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM