Dijsktra用于邻接矩阵,最短和最便宜的路径,单源,单目标

时间:2016-02-20 12:51:27

标签: java graph dijkstra path-finding adjacency-matrix

我正在尝试实现Dijkstra算法,以便从一个顶点到另一个顶点获得最短且最便宜的路径,而不是所有顶点。该图是使用随机连续节点随机构建的。

但要么我得到负成本,要么两种方法的路径,最便宜和最短,是相同的。 我试图通过使用相同的方法找到两个结果,因为最短路径只是忽略权重。这是由布尔变量控制的。

Dijkstra - 班级:

public class Dijkstra {

private Graph graph;
private int[] distance;
private boolean[] visited;
private int[] parents;
private int startNode;
private int endNode;

public Dijkstra(Graph graph, int startNode, int endNode) {
    this.graph = graph;
    distance = new int[graph.getAdjList().length];
    visited = new boolean[graph.getAdjList().length];
    parents = new int[graph.getAdjList().length];
    this.startNode = startNode;
    this.endNode = endNode;
}

public void findPath(boolean isUnweighted) {
    if (endNode == startNode) {
        System.out.println(
                "Starting node  " + startNode + "  and target node " + endNode + " are identical.");
        return;
    }
    System.out.println("Starting node: " + startNode);
    System.out.println("Target node:  " + endNode);
    int[][] adjList = graph.getAdjList();
    int[][] graphForPathFinding = new int[adjList.length][adjList.length];

    if (isUnweighted) {
        // set all weights to 1
        graphForPathFinding = convertGraphToUnweighted(graphForPathFinding);
    } else
        graphForPathFinding = adjList;
    // initialize
    for (int i = 0; i < adjList.length; i++) {
        parents[i] = Integer.MAX_VALUE;
        visited[i] = false;
        distance[i] = Integer.MAX_VALUE;
    }

    distance[startNode] = 0;
    for (int i = 0; i < graphForPathFinding.length; i++) {

        int nextNode = getMinDistance();
        if (nextNode == -1) { // no path found
            System.out.println(
                    "No path found between " + startNode + " and " + endNode);
            return;
        }
        visited[nextNode] = true;
        parents[i] = nextNode;

        if (nextNode == endNode) {
            printResults();
            return; // target node reached
        }
        int[] neighbors = graph.getNeighbors(nextNode);
        for (int j = 0; j < neighbors.length; j++) {

             if (!visited[j] && neighbors[j] > 0 && distance[nextNode] !=
             Integer.MAX_VALUE
             && distance[nextNode] + neighbors[j] < distance[j])
             distance[j] = distance[nextNode] + neighbors[j];
        }

    }

}

private int getMinDistance() {
    int min = Integer.MAX_VALUE;
    int min_index = -1;

    for (int i = 0; i < graph.getAdjList().length; i++) {
        if (visited[i] == false && distance[i] <= min) {
            min = distance[i];
            min_index = i;
        }

    }
    return min_index;
}

private int[][] convertGraphToUnweighted(int[][] graphForConverting) {
    for (int i = 0; i < graph.getAdjList().length; i++) {
        for (int j = 0; j < graph.getAdjList()[i].length; j++) {
             //if (graph.getAdjList()[i][j] > 0) {
            graphForConverting[i][j] = 1;
        // }
        }
    }
    return graphForConverting;
}

private void printResults() {
int weight = 0;
int steps = 0;
System.out.println("Pfad: ");
    for(int i = endNode; i>=0; i--){
        if(parents[i] < Integer.MAX_VALUE){
            System.out.print(parents[i] + "    ");
            steps++;
            weight += graph.getAdjList()[i][parents[i]];
        }

    }

    System.out.println();
    System.out.println("Number of nodes: " + steps);
     System.out.println("Weight:  " + weight);
}

}

图表 - 类getNeighbors

public int[] getNeighbors(int node){
        int neighborCount = 0;
        for(int i = 0; i < adjList[node].length; ++i)
            if(adjList[node][i] > 0)
                ++neighborCount;
        int[] neighbours = new int[neighborCount];
        neighborCount = 0;
        for(int i = 0; i < adjList[node].length; ++i)
            if(adjList[node][i] > 0)
                neighbours[neighborCount++] = i;

        return neighbours;
    }

主要方法:

 public static void main(String[] args) {
            int startNode = rnd.nextInt(graph.getAdjList().length);
            int endNode = rnd.nextInt(graph.getAdjList().length);
            Dijkstra d = new Dijkstra(graph, startNode, endNode);

            System.out.println("Shortest path:");
            d.findPath(true); // true = unweighted, false = weighted
            System.out.println();
            System.out.println("Cheapest path:");
            d.findPath(false);
}

1 个答案:

答案 0 :(得分:2)

好的,我花了一些时间来弄清楚你的算法为什么以及如何被破坏,因为有很多错误:

<强> 1。 getMinDistance()错误

在这种方法中,你试图找到下一个访问最便宜的节点,这是正确的想法,但实现是错误的。首先,您要考虑图中的所有节点,而不仅仅是您当前访问的节点的邻居,其次使用distance数组来查找成本。但是在那里,所有未访问节点的值都是Integer.MAX_VALUE,因此该方法将始终选择索引最高的节点。

<强> 2。您使用的是错误的附属列表

对于最短路径,您正在创建原始邻接列表的修改副本,但之后您没有使用它。

第3。您修改的Adjancency List错误

在为最短路径创建修改后的副本时,您将值设置为1,而不是1哪里有边缘,Integer.MAX_VALUE用于其他所有内容(实际上您应该使用{在这种情况下{1}}并在您的代码中检查它。否则您的算法将说明断开的节点之间存在路径。

<强> 4。这不是Dijkstra

我花了一段时间才看到这一点,因为有时你会得到正确的结果,但这不是Dijkstra's Algorithm。要正确实现它,您需要一个优先级队列或一些其他机制来跟踪距离并获得最小值。你试着用你的getMinDistance&#39;方法,但这种方法是错误的,因为你考虑了图中的所有节点,而不仅仅是队列中的那些节点。

有关代码的固定版本,请参阅下文。你应该尝试自己重新实现它,但是因为我现在已经拥有了它...

-1
相关问题