180 likes | 389 Views
Pertemuan 24 Shortest Path. Matakuliah : T0026/Struktur Data Tahun : 2005 Versi : 1/1. Learning Outcomes. Pada akhir pertemuan ini, diharapkan mahasiswa akan mampu : Mahasiswa dapat memilih algoritma yang tepat dalam memecahkan masalah shortest path. Outline Materi.
E N D
Pertemuan 24Shortest Path Matakuliah : T0026/Struktur Data Tahun : 2005 Versi : 1/1
Learning Outcomes Pada akhir pertemuan ini, diharapkan mahasiswa akan mampu : • Mahasiswa dapat memilih algoritma yang tepat dalam memecahkan masalah shortest path
Outline Materi • Shortest paths Definition • Single source all destinations • Dijkastra's Algorithm • Implementation of Dijkastra's algorithm • Analysis of Dijkastra's algorithm • Example of Dijkastra's algorithm • All pairs shortest paths • Algorithm concept • Example of all pairs shortest paths (APSP)
Single-Source Shortest-Path Definition : Find the shortest paths from a specific source vertex to every other vertex in a weighted, directed graph. Dijkstra's algorithm solves this if all weights are nonnegative. The Bellman-Ford algorithm handles any weights. A. Single Source All Destinations 12 A B 5 10 7 3 2 15 E 13 6 8 4 6 3 C D 8 Given by this graph, which path is shortest path from A to : • B ? • C ? • D ? • E ?
Dijkstra’s Algorithm void shortestpath ( int v, int cost[][MAX_VERTICES], int distance[], int n, shortint found[]) { /* distance[i] represents the shortest path from vertex v to I, found[i] holds a 0 if the shortest path from vertex v has not been found and a 1 if if has, cost is the adjacency matrix */ int i, u, w; for (i=0; i<n; i++) { found[i]=FALSE; /* Vertex[i] is not in S */ distance[i] = coast[v][i]; } found[v] = TRUE; distance[v] = 0; for (i=0; i<n-2; i++) { u=choose( distance, n, found); found[u] = TRUE; for (w=0; w<n; w++) if (!found[w]) if (distance[u] + cost[u][w] < distance[w]) distance[w] = distance[u] + cost[u][w]; } }
int choose ( int distance[], int n, shortint found[]) { /* find the smallest distance not yet checked */ int i, min, minpos; min = INT_MAX; minpos = -1; for (i=0; i<n; i++) { if (distance[i] < min && !found[i]) { min = distance[i]; minpos =I; } return minpos; }
12 A B 5 10 7 6 13 15 2 E 3 8 4 6 3 C D 8 • Vo = A • 999 indicates the maximum number • Found [i] = False (F), vertices [i] is not in S • Found [i] = True (T), vertices [i] is in S
Found [v] = True, Distance [v]=0 Found [2] = True
Shortest-Path From Vertex A to All Destinations 12 A B 5 10 7 6 13 15 2 E 3 8 4 6 3 C D 8 A B 10 2 E 8 4 C D
In the APSP problem we must find the shortest paths between all pairs of vertices, Vi, Vj, i ≠ j. We could solve this problem using shortest path with each of the vertices in V(G) as the source. All Pair Shortest Paths (APSP) j 6 V0 V1 4 11 3 i 2 V2 Distance [i][k] + Distance [k][j] < Distance [i][j] => Distance [i][j] = Distance [i][k] + Distance [k][j]