Algorithmus von Dijkstra: Unterschied zwischen den Versionen

GISWiki - Das freie Portal für Geoinformatik (GIS)
Wechseln zu: Navigation, Suche
(Code)
(Code)
Zeile 181: Zeile 181:
 
Implementations in various programming languages of Dijkstra's algorithm.
 
Implementations in various programming languages of Dijkstra's algorithm.
  
===[http://en.wikipedia.org/wiki/C_programming_language C]===
+
===[[C]]===
<C>
+
<c>
 
  void dodijkstra(int sr,int ds,int path[])
 
  void dodijkstra(int sr,int ds,int path[])
 
  {
 
  {
Zeile 238: Zeile 238:
 
  path[i]=k;
 
  path[i]=k;
 
  }
 
  }
</C>
+
</c>
 +
 
 +
===[[C_plus_plus|C++]]===
 +
 
 +
===[[Actionscript]]===
 +
 
 +
===[[Python]]===
 +
 
 +
===[[PHP]]===
 +
==== Usage Example====
 +
 
 +
===[[Visual Basic]] 6===
 +
==== Example Data ====

Version vom 5. März 2006, 18:09 Uhr

Deutsch

Der Algorithmus von Dijkstra (nach seinem Erfinder Edsger W. Dijkstra) dient der Berechnung eines kürzesten Pfades zwischen einem Startknoten und einem beliebigen Knoten in einem kantengewichteten Graphen. Die Gewichte dürfen dabei nicht negativ sein. Für Graphen mit negativen Gewichten aber ohne negative Zyklen ist der Bellman-Ford-Algorithmus geeignet.

Für nicht zusammenhängende, ungerichtete Graphen kann der Abstand zu bestimmten Knoten auch unendlich sein, wenn ein Pfad zwischen Startknoten und diesen Knoten nicht existiert. Dasselbe gilt auch für gerichtete, nicht stark zusammenhängende Graphen.

Algorithmus

G bezeichnet den gewichteten Graphen mit V (engl. vertex) als Knotenmenge, E (engl. edge) als Kantenmenge und Kosten als Gewichtsfunktion. s ist der Startknoten, U (engl. unvisited) ist die Menge der noch zu bearbeitenden Knoten und z ist ggf. ein spezieller Zielknoten, bei dem abgebrochen werden kann, wenn seine Distanz zum Startknoten bekannt ist.

Nach Ende des Algorithmus enthält Distanz die Abstände aller Knoten zu s. In Vorgänger ist ein spannender Baum der von s aus ausgehenden minimalen Wege in Form eines In-Tree gespeichert.

Wird bei Erreichen von z abgebrochen (mit #optional gekennzeichet), so enthalten Distanz und Vorgänger diese Werte nur für alle zuvor betrachteten Knoten. Dies sind mindestens die, die kleineren Abstand als z zu s besitzen.

01  für jedes v aus V
02      Distanz(v) := unendlich, Vorgänger(v) := kein
03  Distanz(s) := 0, Vorgänger(s) := 'begin', U := V
04  M := EMPTYSET 
05  für jedes (s,v) aus E mit v aus U
06      Distanz(v) := Kosten(s,v) 
07      M := M UNION {v}
08      Vorgänger(v) := s
09
10  solange M nicht leer
11      wähle u aus M mit Distanz(u) minimal                               
12      M := M - {u}  
13      U := U - {u}                                              
14      wenn u = z dann STOP   # optional
15      für jedes (u,v) aus E mit v aus U
16          M := M UNION {v} 
17          wenn Distanz(u) + Kosten(u,v) < Distanz(v) dann
18              Distanz(v) := Distanz(u) + Kosten(u,v)
19              Vorgänger(v) := u

Grundlegende Konzepte und Verwandtschaften

Der Algorithmus gehört zur Klasse der Greedy-Algorithmen. Sukzessive wird der nächstbeste Knoten, der einen kürzesten Pfad besitzt (Zeile 06), in eine Ergebnismenge aufgenommen und aus der Menge der noch zu bearbeitenden Knoten entfernt (Zeile 07). Damit findet sich eine Verwandtschaft zur Breitensuche, die ebenfalls solch ein gieriges Verhalten aufweist.

Ein alternativer Algorithmus zur Suche kürzester Pfade, der sich dagegen auf das Optimalitätsprinzip von Bellman stützt, ist der Floyd-Warshall-Algorithmus. Das Optimalitätsprinzip besagt, dass, wenn der kürzeste Pfad von A nach C über B führt, der Teilpfad A B auch der kürzeste Pfad von A nach B sein muss.

Ein weiterer alternativer Algorithmus ist der [[de:A*-Algorithmus|]], der den Algorithmus von Dijkstra um eine Abschätzfunktion erweitert. Falls diese gewisse Eigenschaften erfüllt, kann damit der kürzeste Pfad unter Umständen schneller gefunden werden.


Berechnung eines Spannbaumes

Negative Kante sorgt für Unklarheiten bei Knoten a

Nach Ende des Algorithmus ist in Vorgänger ein spannender Baum der Komponente von s aus kürzesten Pfaden von s zu allen Knoten der Komponente verzeichnet. Dieser Baum ist jedoch nicht notwendigerweise auch minimal, wie die Abbildung zeigt:

Sei x eine Zahl größer 0. Minimal spannende Bäume sind entweder durch die Kanten {a,s} und {a,b} oder {b,s} und {a,b) gegeben. Die Gesamtkosten eines minimal spannenden Baumes betragen 2+x. Dijkstras Algorithmus liefert mit Startpunkt s die Kanten {a,s} und {b,s} als Ergebnis. Die Gesamtkosten dieses spannenden Baumes betragen 2+2x.

Die Berechnung eines minimalen Spannbaumes ist mit dem Algorithmus von Prim oder dem Algorithmus von Kruskal möglich.

Zeitkomplexität

Im Folgenden sei m die Anzahl der Kanten und n die Anzahl der Knoten. Der Algorithmus von Dijkstra muss n mal den nächsten minimalen Knoten u bestimmen (Zeilen 05 und 06). Eine Möglichkeit wäre jedes Mal diesen mittels Durchlaufen durch eine Knotenliste zu bestimmen. Die Laufzeit beträgt dann <math>O(n^2)</math>. Eine effizientere Möglichkeit zur Liste bietet die Verwendung der Datenstruktur Fibonacci-Heap. Die Laufzeit beträgt dann lediglich <math>O(m+n\cdot\log (n))</math>.

Anwendungen

Routenplaner sind ein prominentes Beispiel, bei dem dieser Algorithmus eingesetzt werden kann. Der Graph repräsentiert hier das Straßennetz, welches verschiedene Punkte miteinander verbindet. Gesucht ist die kürzeste Route zwischen zwei Punkten.

Dijkstras Algorithmus wird auch im Internet als Routing-Algorithmus in OSPF eingesetzt.

Siehe auch

Literatur

  • E. W. Dijkstra: A note on two problems in connexion with graphs. In: Numerische Mathematik. 1 (1959), S. 269–271

Weblinks

English

Dijkstra's algorithm, named after its discoverer, Dutch computer scientist Edsger Dijkstra, is an algorithm that solves the single-source shortest path problem for a directed graph with nonnegative edge weights.

For example, if the vertices of the graph represent cities and edge weights represent driving distances between pairs of cities connected by a direct road, Dijkstra's algorithm can be used to find the shortest route between two cities.

The input of the algorithm consists of a weighted directed graph G and a source vertex s in G. We will denote V the set of all vertices in the graph G. Each edge of the graph is an ordered pair of vertices (u,v) representing a connection from vertex u to vertex v. The set of all edges is denoted E. Weights of edges are given by a weight function w: E → [0, ∞]; therefore w(u,v) is the non-negative cost of moving from vertex u to vertex v. The cost of an edge can be thought of as (a generalization of) the distance between those two vertices. The cost of a path between two vertices is the sum of costs of the edges in that path. For a given pair of vertices s and t in V, the algorithm finds the path from s to t with lowest cost (i.e. the shortest path). It can also be used for finding costs of shortest paths from a single vertex s to all other vertices in the graph.

Description of the algorithm

The algorithm works by keeping for each vertex v the cost d[v] of the shortest path found so far between s and v. Initially, this value is 0 for the source vertex s (d[s]=0), and infinity for all other vertices, representing the fact that we do not know any path leading to those vertices (d[v]=? for every v in V, except s). When the algorithm finishes, d[v] will be the cost of the shortest path from s to v -- or infinity, if no such path exists. The basic operation of Dijkstra's algorithm is edge relaxation: if there is an edge from u to v, then the shortest known path from s to u (d[u]) can be extended to a path from s to v by adding edge (u,v) at the end. This path will have length d[u]+w(u,v). If this is less than the current d[v], we can replace the current value of d[v] with the new value.

Edge relaxation is applied until all values d[v] represent the cost of the shortest path from s to v. The algorithm is organized so that each edge (u,v) is relaxed only once, when d[u] has reached its final value.

The algorithm maintains two sets of vertices S and Q. Set S contains all vertices for which we know that the value d[v] is already the cost of the shortest path and set Q contains all other vertices. Set S starts empty, and in each step one vertex is moved from Q to S. This vertex is chosen as the vertex with lowest value of d[u]. When a vertex u is moved to S, the algorithm relaxes every outgoing edge (u,v).

Pseudocode

In the following algorithm, u := Extract_Min(Q) searches for the vertex u in the vertex set Q that has the least d[u] value. That vertex is removed from the set Q and returned to the user.

 1  function Dijkstra(G, w, s)
 2     for each vertex v in V[G]                        // Initializations
 3           d[v] := infinity
 4           previous[v] := undefined
 5     d[s] := 0
 6     S := empty set
 7     Q := set of all vertices
 8     while Q is not an empty set                      // The algorithm itself
 9           u := Extract_Min(Q)
10           S := S union {u}
11           for each edge (u,v) outgoing from u
12                  if d[v] > d[u] + w(u,v)             // Relax (u,v)
13                        d[v] := d[u] + w(u,v)
14                        previous[v] := u

If we are only interested in a shortest path between vertices s and t, we can terminate the search at line 9 if u = t.

Now we can read the shortest path from s to t by iteration:

1 S := empty sequence 
2 u := t
3 while defined u                                        
4       insert u to the beginning of S
5       u := previous[u]

Now sequence S is the list of vertices on the shortest path from s to t.

Running time

We can express the running time of Dijkstra's algorithm on a graph with m edges and n vertices as a function of m and n using the Big O notation.

The simplest implementation of the Dijkstra's algorithm stores vertices of set Q in an ordinary linked list or array, and operation Extract-Min(Q) is simply a linear search through all vertices in Q. In this case, the running time is O(n2).

For sparse graphs, that is, graphs with much less than n2 edges, Dijkstra's algorithm can be implemented more efficiently by storing the graph in the form of adjacency lists and using a binary heap or Fibonacci heap as a priority queue to implement the Extract-Min function. With a binary heap, the algorithm requires O((m+n)log n) time, and the Fibonacci heap improves this to O(m + n log n).

Related problems and algorithms

The functionality of Dijkstra's original algorithm can be extended with a variety of modifications. For example, sometimes it is desirable to present solutions which are less than mathematically optimal. To obtain a ranked list of less-than-optimal solutions, the optimal solution is first calculated. A single edge appearing in the optimal solution is removed from the graph, and the optimum solution to this new graph is calculated. Each edge of the original solution is suppressed in turn and a new shortest-path calculated. The secondary solutions are then ranked and presented after the first optimal solution.

OSPF (open shortest path first) is a well known real-world implementation of Dijkstra's algorithm used in internet routing.

Unlike Dijkstra's algorithm, the Bellman-Ford algorithm can be used on graphs with negative edge weights, as long as the graph contains no negative cycle reachable from the source vertex s. (The presence of such cycles means there is no shortest path, since the total weight becomes lower each time the cycle is traversed.)

A related problem is the traveling salesman problem, which is the problem of finding the shortest path that goes through every vertex exactly once, and returns to the start. This problem is NP-hard; in other words, unlike the shortest path problem, it is unlikely to be solved by a polynomial-time algorithm.

If additional information is available that estimates the "distance" to the target, the A* algorithm can be used instead to cut down on the size of the subset of the graph which is explored.

Literatur / Literature

Weblinks

Code

Implementations in various programming languages of Dijkstra's algorithm.

C

<c>

void dodijkstra(int sr,int ds,int path[])
{
        struct node
	{
	  int pre;   /* Predecessor */
	  int length; /* Length between the nodes */
	  enum {perm,tent} label; /* Enumeration for permanent and tentative labels */
	}state[MAX];
	
	int i,k,min;
	struct node *p;
	/* Initialisation of the nodes aka First step of Dijkstra Algo */
	for(p=&state[0];p<&state[no_nodes];p++)
	{
           p->pre= -1;
	   p->length=INFTY;
	   p->label=tent;
	}
	state[ds].length=0; /* Destination length set to zero */
	state[ds].label=perm; /* Destination set to be the permanent node */
	k=ds; /* initial working node */
	/* Checking for a better path from the node k ? */
	do
	{
           for(i=0;i<no_nodes;i++)
	      {
		  if(dist[k][i]!=0 && state[i].label==tent)
		     {
			if((state[k].length+dist[k][i])<state[i].length)
			   {
			       state[i].pre=k;
			       state[i].length=state[k].length+dist[k][i];
		           }
		     }
	      }
             k=0;
             min=INFTY;
	      /* Find a node which is tentatively labeled and with minimum label */
	      for(i=0;i<no_nodes;i++)
	      {
		 if(state[i].label==tent && state[i].length<min)
		    {
			min=state[i].length;
			k=i;
		    }
	      }
	      state[k].label=perm;
	} while(k!=sr);
	
	i=0;
	k=sr;
	/* Print the path to the output array */
	do {path[i++]=k;k=state[k].pre;} while(k>=0);
	path[i]=k;
}

</c>

C++

Actionscript

Python

PHP

Usage Example

Visual Basic 6

Example Data