SlideShare a Scribd company logo
1 of 29
All Pairs Shortest Paths and
Floyd-Warshall Algorithm
CLRS 25.2
All-pairs shortest paths
• Given a weighted directed graph, G(V, E) with a weight
function w that maps edges to real-valued weights.
– w(u,v) denote the weight of an edge (u,v)
• For every pair of vertices u, v, find a shortest path from u to
v, where the weight of a path is the sum of the weights of
the edges along the path.
– Run Dijkstra’s algorithm V times?
– O(V E log V) if no negative weights
All-pairs shortest paths
• If we allow negative edge weights but no negative-weight
cycles
– Cannot use Dijkstra’ algorithm
– Run Bellman-Ford (the one we did not cover) once for each vertex,
which leads to a running time of
for a dense graph.
)
(
)
( 4
2
V
O
E
V
O 
All-pairs shortest paths
• Instead, we will use a dynamic programming solution:
– Floyd-Warshall Algorithm
– Running time:
• Let denote the weight of the shortest path
from u to v
)
,
( v
u

)
( 3
V
O
Input: adjacency matrix representing G
• Assume an adjacency matrix representation
– Assume vertices are numbered 1,2,…,n
– The input is a n x n matrix representing the edge
weights of an n-vertex directed graph
E
j
i
j
i
E
j
i
j
i
j
i
INF
j
i
w
wij











)
,
(
and
if
)
,
(
and
if
if
)
,
(
0
)
( ij
w
W 
Output?
• n x n matrix
• Entry will contain the weight of the shortest path
from vertex i to vertex j, that is
)
( ij
d
D 
ij
d
)
,
( j
i
dij 

Example: input
2
1
5
3
4
3
4
8
-4
6
2
1 -5
7
0 3 8 ∞ -4
∞ 0 ∞ 1 7
∞ 4 0 ∞ ∞
2 ∞ -5 0 ∞
∞ ∞ ∞ 6 0
1 2 3 4 5
1
2
3
4
5
W
Example: output
2
1
5
3
4
3
4
8
-4
6
2
1 -5
7
0 1 -3 2 -4
3 0 -4 1 -1
7 4 0 5 3
2 -1 -5 0 -2
8 5 1 6 0
1 2 3 4 5
1
2
3
4
5
D
Example: output
2
1
5
3
4
3
4
8
-4
6
2
1 -5
7
0 1 -3 2 -4
3 0 -4 1 -1
7 4 0 5 3
2 -1 -5 0 -2
8 5 1 6 0
1 2 3 4 5
1
2
3
4
5
D
Example: output
2
1
5
3
4
3
4
8
-4
6
2
1 -5
7
0 1 -3 2 -4
3 0 -4 1 -1
7 4 0 5 3
2 -1 -5 0 -2
8 5 1 6 0
1 2 3 4 5
1
2
3
4
5
D
DP Formulation
• Intermediate vertices: on a path
any vertex other than the first and the last vertices is called
and intermediate vertex.
• Let vertices of G be V={1,2,….,n}
• Consider a subset {1,2,…,k} of these vertices for some k
• Subproblems: limit the set of intermediate vertices on a
path from i to j to subset {1,2,…,k}
– The path is allowed to pass through only vertices 1
through k

 l
v
v
v
p ,...,
, 2
1
DP Formulation
• In the original problem: For any pair of vertices i and j, the
intermediate vertices could be drawn from the set {1,…,n}
• Define to be the shortest path from i to j such that
intermediate vertices on the path are drawn from the set
{1,2,…,k}
– Matrix
)
(k
ij
d
)
(k
D
Example
2
1
5
3
4
3
4
8
14
6
2
1 -5
7
16
)
1
(
45
)
0
(
45



d
d
Example
2
1
5
3
4
3
4
8
14
6
2
1 -5
7
12
)
2
(
45 
d
Example
2
1
5
3
4
3
4
8
14
6
2
1 -5
7
6
)
3
(
45 
d
DP Formulation
• How to reduce to smaller problems? i.e. how to
compute assuming we have already computed ?
)
(k
ij
d
)
(k
ij
d )
1
( 
k
D
DP Formulation
• How to reduce to smaller problems? i.e. how to
compute assuming we have already computed ?
• Two cases:
Case 1: Vertex k is NOT among the intermediate vertices
on the shortest path from i to j
)
(k
ij
d
)
(k
ij
d )
1
( 
k
D
)
1
(
)
( 
 k
ij
k
ij d
d
DP Formulation
Case 2: Vertex k is an intermediate vertex on the shortest
path from i to j
– First take the shortest path from i to k using intermediate vertices
from the set {1,2,…,k-1}
– Then take the shortest path from k to j using intermediate vertices
from the set {1,2,…,k-1}
)
1
(
)
1
(
)
( 


 k
kj
k
ik
k
ij d
d
d
i
k
j
DP Formulation
• Base case:
• Recursive definition (for k > 0)
ij
ij w
d 
)
0
(
)
,
min( )
1
(
)
1
(
)
1
(
)
( 



 k
kj
k
ik
k
ij
k
ij d
d
d
d
Floyd-Warshall Algorithm
Floyd-Warshall(W) {
n = rows[W]
for k=1 to n do
for i=1 to n do
for j=1 to n do
return
}
W
D 
)
0
(
)
,
min( )
1
(
)
1
(
)
1
(
)
( 



 k
kj
k
ik
k
ij
k
ij d
d
d
d
)
(n
D
)
( 3
n
O
Example
2
1
5
3
4
3
4
8
-4
6
2
1 -5
7
0 3 8 ∞ -4
∞ 0 ∞ 1 7
∞ 4 0 ∞ ∞
2 ∞ -5 0 ∞
∞ ∞ ∞ 6 0
1 2 3 4 5
1
2
3
4
5
W
D 
)
0
(
Example
2
1
5
3
4
3
4
8
-4
6
2
1 -5
7
0 3 8 ∞ -4
∞ 0 ∞ 1 7
∞ 4 0 ∞ ∞
2 5 -5 0 -2
∞ ∞ ∞ 6 0
1 2 3 4 5
1
2
3
4
5
)
1
(
D
Example
2
1
5
3
4
3
4
8
-4
6
2
1 -5
7
0 3 8 4 -4
∞ 0 ∞ 1 7
∞ 4 0 5 11
2 5 -5 0 -2
∞ ∞ ∞ 6 0
1 2 3 4 5
1
2
3
4
5
)
2
(
D
Example
2
1
5
3
4
3
4
8
-4
6
2
1 -5
7
0 3 8 4 -4
∞ 0 ∞ 1 7
∞ 4 0 5 11
2 -1 -5 0 -2
∞ ∞ ∞ 6 0
1 2 3 4 5
1
2
3
4
5
)
3
(
D
Example
2
1
5
3
4
3
4
8
-4
6
2
1 -5
7
0 3 -1 4 -4
3 0 -4 1 -1
7 4 0 5 3
2 -1 -5 0 -2
8 5 1 6 0
1 2 3 4 5
1
2
3
4
5
)
4
(
D
Example
2
1
5
3
4
3
4
8
-4
6
2
1 -5
7
0 1 -3 2 -4
3 0 -4 1 -1
7 4 0 5 3
2 -1 -5 0 -2
8 5 1 6 0
1 2 3 4 5
1
2
3
4
5
)
5
(
D
Space Requirement
• Do we need n matrices, each of n x n?
– One n x n matrix for D is enough!
– In phase k, it is okay to overwrite the D from the previous
phase (k-1)
– Why?
Floyd-Warshall(W) {
n = rows[W]
for i=1 to n do
for j = 1 to n do
D[i,j] = W[i,j]
for k=1 to n do
for i=1 to n do
for j=1 to n do
if (D[i,k]+D[k,j] < D[i,j])
D[i,j]=D[i,k}+D[k,j]
return D
}
Homework: How to extract the path?
• How should we modify the algorithm to store additional
information which then can be used to extract the path?

More Related Content

Similar to 4900514.ppt

Jaimin chp-5 - network layer- 2011 batch
Jaimin   chp-5 - network layer- 2011 batchJaimin   chp-5 - network layer- 2011 batch
Jaimin chp-5 - network layer- 2011 batchJaimin Jani
 
An optimal and progressive algorithm for skyline queries slide
An optimal and progressive algorithm for skyline queries slideAn optimal and progressive algorithm for skyline queries slide
An optimal and progressive algorithm for skyline queries slideWooSung Choi
 
Randomized algorithms all pairs shortest path
Randomized algorithms  all pairs shortest pathRandomized algorithms  all pairs shortest path
Randomized algorithms all pairs shortest pathMohammad Akbarizadeh
 
Self Managed and Automatically Reconfigurable Stream Processing - Vasiliki Ka...
Self Managed and Automatically Reconfigurable Stream Processing - Vasiliki Ka...Self Managed and Automatically Reconfigurable Stream Processing - Vasiliki Ka...
Self Managed and Automatically Reconfigurable Stream Processing - Vasiliki Ka...Flink Forward
 
Self-managed and automatically reconfigurable stream processing
Self-managed and automatically reconfigurable stream processingSelf-managed and automatically reconfigurable stream processing
Self-managed and automatically reconfigurable stream processingVasia Kalavri
 
Oil Spill Simulation near The Red Sea Coast using The Random Walk Technique
Oil Spill Simulation near The Red Sea Coast using The Random Walk TechniqueOil Spill Simulation near The Red Sea Coast using The Random Walk Technique
Oil Spill Simulation near The Red Sea Coast using The Random Walk TechniqueAmro Elfeki
 
Chap10 slides
Chap10 slidesChap10 slides
Chap10 slidesHJ DS
 
Some Continued Mock Theta Functions from Ramanujan’s Lost Notebook (IV)
Some Continued Mock Theta Functions from Ramanujan’s Lost Notebook (IV)Some Continued Mock Theta Functions from Ramanujan’s Lost Notebook (IV)
Some Continued Mock Theta Functions from Ramanujan’s Lost Notebook (IV)paperpublications3
 
All Pair shortest Path.pptx
All Pair shortest Path.pptxAll Pair shortest Path.pptx
All Pair shortest Path.pptxSayaliKawale2
 
Special Products and Factoring , Rational Algebraic Expressions Concept Map
Special Products and Factoring , Rational Algebraic Expressions Concept MapSpecial Products and Factoring , Rational Algebraic Expressions Concept Map
Special Products and Factoring , Rational Algebraic Expressions Concept MapRocyl Anne Javagat
 
A presentation on prim's and kruskal's algorithm
A presentation on prim's and kruskal's algorithmA presentation on prim's and kruskal's algorithm
A presentation on prim's and kruskal's algorithmGaurav Kolekar
 
prims and Kruskal 1.pdf
prims and Kruskal 1.pdfprims and Kruskal 1.pdf
prims and Kruskal 1.pdfDEEPAK948083
 
PSLDoc: Protein subcellular localization prediction based on gapped-dipeptide...
PSLDoc: Protein subcellular localization prediction based on gapped-dipeptide...PSLDoc: Protein subcellular localization prediction based on gapped-dipeptide...
PSLDoc: Protein subcellular localization prediction based on gapped-dipeptide...JIA-MING CHANG
 

Similar to 4900514.ppt (20)

Merge sort-algorithm for computer science engineering students
Merge sort-algorithm for computer science engineering studentsMerge sort-algorithm for computer science engineering students
Merge sort-algorithm for computer science engineering students
 
Jaimin chp-5 - network layer- 2011 batch
Jaimin   chp-5 - network layer- 2011 batchJaimin   chp-5 - network layer- 2011 batch
Jaimin chp-5 - network layer- 2011 batch
 
An optimal and progressive algorithm for skyline queries slide
An optimal and progressive algorithm for skyline queries slideAn optimal and progressive algorithm for skyline queries slide
An optimal and progressive algorithm for skyline queries slide
 
Randomized algorithms all pairs shortest path
Randomized algorithms  all pairs shortest pathRandomized algorithms  all pairs shortest path
Randomized algorithms all pairs shortest path
 
Self Managed and Automatically Reconfigurable Stream Processing - Vasiliki Ka...
Self Managed and Automatically Reconfigurable Stream Processing - Vasiliki Ka...Self Managed and Automatically Reconfigurable Stream Processing - Vasiliki Ka...
Self Managed and Automatically Reconfigurable Stream Processing - Vasiliki Ka...
 
Self-managed and automatically reconfigurable stream processing
Self-managed and automatically reconfigurable stream processingSelf-managed and automatically reconfigurable stream processing
Self-managed and automatically reconfigurable stream processing
 
Oil Spill Simulation near The Red Sea Coast using The Random Walk Technique
Oil Spill Simulation near The Red Sea Coast using The Random Walk TechniqueOil Spill Simulation near The Red Sea Coast using The Random Walk Technique
Oil Spill Simulation near The Red Sea Coast using The Random Walk Technique
 
Chap10 slides
Chap10 slidesChap10 slides
Chap10 slides
 
UNIT I_1.pdf
UNIT I_1.pdfUNIT I_1.pdf
UNIT I_1.pdf
 
Some Continued Mock Theta Functions from Ramanujan’s Lost Notebook (IV)
Some Continued Mock Theta Functions from Ramanujan’s Lost Notebook (IV)Some Continued Mock Theta Functions from Ramanujan’s Lost Notebook (IV)
Some Continued Mock Theta Functions from Ramanujan’s Lost Notebook (IV)
 
All Pair shortest Path.pptx
All Pair shortest Path.pptxAll Pair shortest Path.pptx
All Pair shortest Path.pptx
 
Special Products and Factoring , Rational Algebraic Expressions Concept Map
Special Products and Factoring , Rational Algebraic Expressions Concept MapSpecial Products and Factoring , Rational Algebraic Expressions Concept Map
Special Products and Factoring , Rational Algebraic Expressions Concept Map
 
UNIT I_2.pdf
UNIT I_2.pdfUNIT I_2.pdf
UNIT I_2.pdf
 
A presentation on prim's and kruskal's algorithm
A presentation on prim's and kruskal's algorithmA presentation on prim's and kruskal's algorithm
A presentation on prim's and kruskal's algorithm
 
FEMSlide 1.pdf
FEMSlide 1.pdfFEMSlide 1.pdf
FEMSlide 1.pdf
 
prims and Kruskal 1.pdf
prims and Kruskal 1.pdfprims and Kruskal 1.pdf
prims and Kruskal 1.pdf
 
Merge sort algorithm power point presentation
Merge sort algorithm power point presentationMerge sort algorithm power point presentation
Merge sort algorithm power point presentation
 
Ppt 1
Ppt 1Ppt 1
Ppt 1
 
Topological Sort
Topological SortTopological Sort
Topological Sort
 
PSLDoc: Protein subcellular localization prediction based on gapped-dipeptide...
PSLDoc: Protein subcellular localization prediction based on gapped-dipeptide...PSLDoc: Protein subcellular localization prediction based on gapped-dipeptide...
PSLDoc: Protein subcellular localization prediction based on gapped-dipeptide...
 

Recently uploaded

Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 

Recently uploaded (20)

Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 

4900514.ppt

  • 1. All Pairs Shortest Paths and Floyd-Warshall Algorithm CLRS 25.2
  • 2. All-pairs shortest paths • Given a weighted directed graph, G(V, E) with a weight function w that maps edges to real-valued weights. – w(u,v) denote the weight of an edge (u,v) • For every pair of vertices u, v, find a shortest path from u to v, where the weight of a path is the sum of the weights of the edges along the path. – Run Dijkstra’s algorithm V times? – O(V E log V) if no negative weights
  • 3. All-pairs shortest paths • If we allow negative edge weights but no negative-weight cycles – Cannot use Dijkstra’ algorithm – Run Bellman-Ford (the one we did not cover) once for each vertex, which leads to a running time of for a dense graph. ) ( ) ( 4 2 V O E V O 
  • 4. All-pairs shortest paths • Instead, we will use a dynamic programming solution: – Floyd-Warshall Algorithm – Running time: • Let denote the weight of the shortest path from u to v ) , ( v u  ) ( 3 V O
  • 5. Input: adjacency matrix representing G • Assume an adjacency matrix representation – Assume vertices are numbered 1,2,…,n – The input is a n x n matrix representing the edge weights of an n-vertex directed graph E j i j i E j i j i j i INF j i w wij            ) , ( and if ) , ( and if if ) , ( 0 ) ( ij w W 
  • 6. Output? • n x n matrix • Entry will contain the weight of the shortest path from vertex i to vertex j, that is ) ( ij d D  ij d ) , ( j i dij  
  • 7. Example: input 2 1 5 3 4 3 4 8 -4 6 2 1 -5 7 0 3 8 ∞ -4 ∞ 0 ∞ 1 7 ∞ 4 0 ∞ ∞ 2 ∞ -5 0 ∞ ∞ ∞ ∞ 6 0 1 2 3 4 5 1 2 3 4 5 W
  • 8. Example: output 2 1 5 3 4 3 4 8 -4 6 2 1 -5 7 0 1 -3 2 -4 3 0 -4 1 -1 7 4 0 5 3 2 -1 -5 0 -2 8 5 1 6 0 1 2 3 4 5 1 2 3 4 5 D
  • 9. Example: output 2 1 5 3 4 3 4 8 -4 6 2 1 -5 7 0 1 -3 2 -4 3 0 -4 1 -1 7 4 0 5 3 2 -1 -5 0 -2 8 5 1 6 0 1 2 3 4 5 1 2 3 4 5 D
  • 10. Example: output 2 1 5 3 4 3 4 8 -4 6 2 1 -5 7 0 1 -3 2 -4 3 0 -4 1 -1 7 4 0 5 3 2 -1 -5 0 -2 8 5 1 6 0 1 2 3 4 5 1 2 3 4 5 D
  • 11. DP Formulation • Intermediate vertices: on a path any vertex other than the first and the last vertices is called and intermediate vertex. • Let vertices of G be V={1,2,….,n} • Consider a subset {1,2,…,k} of these vertices for some k • Subproblems: limit the set of intermediate vertices on a path from i to j to subset {1,2,…,k} – The path is allowed to pass through only vertices 1 through k   l v v v p ,..., , 2 1
  • 12. DP Formulation • In the original problem: For any pair of vertices i and j, the intermediate vertices could be drawn from the set {1,…,n} • Define to be the shortest path from i to j such that intermediate vertices on the path are drawn from the set {1,2,…,k} – Matrix ) (k ij d ) (k D
  • 16. DP Formulation • How to reduce to smaller problems? i.e. how to compute assuming we have already computed ? ) (k ij d ) (k ij d ) 1 (  k D
  • 17. DP Formulation • How to reduce to smaller problems? i.e. how to compute assuming we have already computed ? • Two cases: Case 1: Vertex k is NOT among the intermediate vertices on the shortest path from i to j ) (k ij d ) (k ij d ) 1 (  k D ) 1 ( ) (   k ij k ij d d
  • 18. DP Formulation Case 2: Vertex k is an intermediate vertex on the shortest path from i to j – First take the shortest path from i to k using intermediate vertices from the set {1,2,…,k-1} – Then take the shortest path from k to j using intermediate vertices from the set {1,2,…,k-1} ) 1 ( ) 1 ( ) (     k kj k ik k ij d d d i k j
  • 19. DP Formulation • Base case: • Recursive definition (for k > 0) ij ij w d  ) 0 ( ) , min( ) 1 ( ) 1 ( ) 1 ( ) (      k kj k ik k ij k ij d d d d
  • 20. Floyd-Warshall Algorithm Floyd-Warshall(W) { n = rows[W] for k=1 to n do for i=1 to n do for j=1 to n do return } W D  ) 0 ( ) , min( ) 1 ( ) 1 ( ) 1 ( ) (      k kj k ik k ij k ij d d d d ) (n D ) ( 3 n O
  • 21. Example 2 1 5 3 4 3 4 8 -4 6 2 1 -5 7 0 3 8 ∞ -4 ∞ 0 ∞ 1 7 ∞ 4 0 ∞ ∞ 2 ∞ -5 0 ∞ ∞ ∞ ∞ 6 0 1 2 3 4 5 1 2 3 4 5 W D  ) 0 (
  • 22. Example 2 1 5 3 4 3 4 8 -4 6 2 1 -5 7 0 3 8 ∞ -4 ∞ 0 ∞ 1 7 ∞ 4 0 ∞ ∞ 2 5 -5 0 -2 ∞ ∞ ∞ 6 0 1 2 3 4 5 1 2 3 4 5 ) 1 ( D
  • 23. Example 2 1 5 3 4 3 4 8 -4 6 2 1 -5 7 0 3 8 4 -4 ∞ 0 ∞ 1 7 ∞ 4 0 5 11 2 5 -5 0 -2 ∞ ∞ ∞ 6 0 1 2 3 4 5 1 2 3 4 5 ) 2 ( D
  • 24. Example 2 1 5 3 4 3 4 8 -4 6 2 1 -5 7 0 3 8 4 -4 ∞ 0 ∞ 1 7 ∞ 4 0 5 11 2 -1 -5 0 -2 ∞ ∞ ∞ 6 0 1 2 3 4 5 1 2 3 4 5 ) 3 ( D
  • 25. Example 2 1 5 3 4 3 4 8 -4 6 2 1 -5 7 0 3 -1 4 -4 3 0 -4 1 -1 7 4 0 5 3 2 -1 -5 0 -2 8 5 1 6 0 1 2 3 4 5 1 2 3 4 5 ) 4 ( D
  • 26. Example 2 1 5 3 4 3 4 8 -4 6 2 1 -5 7 0 1 -3 2 -4 3 0 -4 1 -1 7 4 0 5 3 2 -1 -5 0 -2 8 5 1 6 0 1 2 3 4 5 1 2 3 4 5 ) 5 ( D
  • 27. Space Requirement • Do we need n matrices, each of n x n? – One n x n matrix for D is enough! – In phase k, it is okay to overwrite the D from the previous phase (k-1) – Why?
  • 28. Floyd-Warshall(W) { n = rows[W] for i=1 to n do for j = 1 to n do D[i,j] = W[i,j] for k=1 to n do for i=1 to n do for j=1 to n do if (D[i,k]+D[k,j] < D[i,j]) D[i,j]=D[i,k}+D[k,j] return D }
  • 29. Homework: How to extract the path? • How should we modify the algorithm to store additional information which then can be used to extract the path?