【问题标题】:Printing shortest path in 2D array在二维数组中打印最短路径
【发布时间】:2019-03-31 02:18:29
【问题描述】:

我想打印出这个二维数组中所有可能的路径。我还希望能够编辑路径的起点和终点。我已经想出了如何编辑起点而不是目的地。如何编辑我的代码来解决这个问题?例如,可能所有路径都在 E5 而不是 G5 结束。

public class Test {

    int rowCount;
    int colCount;
    int[][] arrA;
    char [] columnName = {'A', 'B', 'C', 'D', 'E', 'F', 'G'};
    //Constructor
    public Test(int arrA[][]) {
        this.arrA = arrA;
        rowCount = arrA.length;
        colCount = arrA[0].length;
    }

    //Function which prints all possible paths
    public void printAll(int currentRow, int currentColumn, String path) {
        if (currentRow == rowCount - 1) {
            for (int i = currentColumn; i < colCount; i++) {
                path += "->" + columnName[i]+(currentRow+1);
            }
            System.out.println(path);
            return;
        }
        if (currentColumn == colCount - 1) {
            for (int i = currentRow; i <= rowCount - 1; i++) {
                path += "->" + columnName[currentColumn]+(i+1);
            }
            System.out.println(path);
            return;
        }
        if(path.isEmpty())
        {
            path = path + columnName[currentColumn]+(currentRow+1);
        }
        else{
            path = path + "->" + columnName[currentColumn]+(currentRow+1);
        }

        printAll(currentRow + 1, currentColumn, path);
        printAll(currentRow, currentColumn + 1, path);
    }

    //Driver Function
    public static void main(String args[]) {
        int[][] grid = { { 0, 1, 2, 3, 4, 5, 6 },
                      { 1, 2, 3, 4, 5, 6, 7 },
                      { 2, 3, 4, 5, 6, 7, 8 },
                      { 3, 4, 5, 6, 7, 8, 9 },
                      { 4, 5, 6, 7, 8, 9, 10}
                    };
        Test p = new Test(grid);
        p.printAll(0, 0, "");
    }    
}

【问题讨论】:

  • 您的问题与您的标题不符
  • 您是在问如何应用停止条件?

标签: java arrays recursion


【解决方案1】:

我使用了digestra算法来计算最短路径。你可以试试这个

    Set<String> addressSet = your AddressSet;

       int[][] adjacencyMatrix = prepareAdjacencyMatrix(employee, addressSet);

       return new CalculateShortestPath(adjacencyMatrix.length - 1)
                        .calculate(adjacencyMatrix, 1);


      private int[][] prepareAdjacencyMatrix(Employee employee,
                                                   Set<String> addressSet) {
                List<String> addressList = new ArrayList<>();
                addressList.addAll(addressSet);

                int l = addressSet.size();
                int[][] adjacencyMatrix = new int[l + 1][l + 1];

                for (int i = 1; i <= l; i++) {
                    for (int j = 1; j <= l; j++) {
                        if (i == j) {
                            adjacencyMatrix[i][j] = Integer.MAX_VALUE;
                        } else {
                            String key = getAddressKey(addressList.get(i - 1), addressList.get(j - 1), employee.getTransport());
                            String reverseKey = getAddressKey(addressList.get(j - 1), addressList.get(i - 1),
                                    employee.getTransport());

                            if (distanceMatrix.containsKey(key)) {
                                adjacencyMatrix[i][j] = 0;

                            } else if (distanceMatrix.containsKey(reverseKey)) {
                                adjacencyMatrix[i][j] = 0;
                            }
                        }
                    }
                }
                return adjacencyMatrix;
            }

private String getAddressKey(String sourceCity,
                                 String destinationCity, MeansOfTransport transport) {
        return sourceCity + "-" + destinationCity + "-" +
                (nonNull(transport) ? transport.getName() : MeansOfTransport.DRIVING.getName());
    }

            public class CalculateShortestPath {
            private int distances[];
            private Set<Integer> settled;
            private Set<Integer> unsettled;
            private int number_of_nodes;
            private int adjacencyMatrix[][];

            public CalculateShortestPath(int number_of_nodes) {
                this.number_of_nodes = number_of_nodes;
                distances = new int[number_of_nodes + 1];
                settled = new HashSet<>();
                unsettled = new HashSet<>();
                adjacencyMatrix = new int[number_of_nodes + 1][number_of_nodes + 1];
            }

            private void dijkstra_algorithm(int adjacency_matrix[][], int source) {
                int evaluationNode;
                for (int i = 1; i <= number_of_nodes; i++) {
                    System.arraycopy(adjacency_matrix[i], 1, adjacencyMatrix[i], 1, number_of_nodes);
                }

                for (int i = 1; i <= number_of_nodes; i++) {
                    distances[i] = Integer.MAX_VALUE;
                }

                unsettled.add(source);
                distances[source] = 0;
                while (!unsettled.isEmpty()) {
                    evaluationNode = getNodeWithMinimumDistanceFromUnsettled();
                    unsettled.remove(evaluationNode);
                    settled.add(evaluationNode);
                    evaluateNeighbours(evaluationNode);
                }
            }

            private int getNodeWithMinimumDistanceFromUnsettled() {
                Iterator<Integer> iterator = unsettled.iterator();
                int node = iterator.next();
                int min = distances[node];
                for (int i = 1; i <= distances.length; i++) {
                    if (unsettled.contains(i)) {
                        if (distances[i] <= min) {
                            min = distances[i];
                            node = i;
                        }
                    }
                }
                return node;
            }

            private void evaluateNeighbours(int evaluationNode) {
                int edgeDistance = -1;
                int newDistance = -1;

                for (int destinationNode = 1; destinationNode <= number_of_nodes; destinationNode++) {
                    if (!settled.contains(destinationNode)) {
                        if (adjacencyMatrix[evaluationNode][destinationNode] != Integer.MAX_VALUE) {
                            edgeDistance = adjacencyMatrix[evaluationNode][destinationNode];
                            newDistance = distances[evaluationNode] + edgeDistance;
                            if (newDistance < distances[destinationNode]) {
                                distances[destinationNode] = newDistance;
                            }
                            unsettled.add(destinationNode);
                        }
                    }
                }
            }

            public int calculate(int[][] adjacency_matrix, int source) {
                int shortestPath = Integer.MAX_VALUE;

                try {
                    dijkstra_algorithm(adjacency_matrix, source);

                    for (int i = 1; i <= distances.length - 1; i++) {
                        if (distances[i] > 0 && distances[i] < shortestPath) {
                            shortestPath = distances[i];
                        }

                    }
                } catch (InputMismatchException inputMismatch) {
                    System.out.println("Wrong Input Format");
                }

                return shortestPath;
            }
        }

【讨论】:

  • 我不明白答案。只是在完全不同的用例上实现摘要算法的不完整演示?
  • 你为什么这么认为。我已经成功地从二维地址数组中计算出最短距离。我将其发布以供参考,可能您必须自定义位以满足您的要求。请澄清您不理解的部分。 @c0der
  • 如果你能描述一下你使用的类会更有帮助。
  • 首先我将我的地址列表存储到一个集合中,然后使用该地址集合准备一个相邻矩阵。那么自定义类calculateShortest path是digestra算法的修改实现,它使用相邻矩阵找到最短路径。@ Imtiaz Shakil Siddique
  • A.据我了解,问题不在于如何找到最短路径 B。如果是的话,我建议在没有权重的图表上使用 BFS。 C. 我怀疑不是 mcve 的代码的价值,不包括邻接矩阵的结构、addressSet 的含义等基本信息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-22
  • 2015-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-12
  • 1970-01-01
相关资源
最近更新 更多