打印二维阵列中的最短路径

时间:2019-03-31 02:18:30

标签: java arrays recursion

我想打印出此2D数组中所有可能的路径。我还希望能够编辑路径的起点和终点。我已经弄清楚了如何编辑起点,而不是目的地。如何编辑代码以解决此问题?例如,也许所有路径都以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, "");
    }    
}

1 个答案:

答案 0 :(得分:1)

我已经使用摘要算法来计算最短路径。您可以尝试

    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;
            }
        }