You are on page 1of 45

Graphs: Shortest

Paths

Shortest paths

What is the shortest path from a to d?

Shortest paths

BFS

Shortest paths

What is the shortest path from a to d?

3
3

A
1

E
4

Shortest paths

Can we can still use BFS ?

3
3

A
1

E
4

Dijkstras algorithm

Dijkstras algorithm

Dijkstras algorithm

Dijkstras algorithm

Dijkstras algorithm

Single source shortest paths

All of the shortest path algorithms well look


at today are call single source shortest
paths algorithms
Why?

A
1

E
4

1
1

A
1

C
4

Heap

A
B
C
D
E

1
1

A
1

C
4

Heap

B
C
D
E

1
1

A
1

C
4

Heap

B
C
D
E

1
1

A
1

C
4

Heap

C
B
D
E

1
1

A
1

C
4

Heap

C
B
D
E

1
1

A
1

C
4

Heap

C
B
D
E

3
3

1
1

A
1

C
4

1
3

Heap

C
B
D
E

3
3

1
1

A
1

C
4

1
3

Heap

B 3
D
E

3
3

1
1

A
1

C
4

Heap

B 3
D
E

3
3

1
1

A
1

C
4

Heap

B 3
D
E

3
3

1
1

A
1

C
4

Heap

B 2
D
E

2
3

1
1

A
1

C
4

Heap

B 2
D
E

2
3

1
1

A
1

C
4

Heap

B 2
E 5
D

2
3

1
1

A
1

E 5

C
4

Heap

B 2
E 5
D

2
3

1
1

A
1

E 5

C
4

Frontier?

Heap

B 2
E 5
D

2
3

1
1

A
1

E 5

C
4

All nodes reachable


from starting node
within a given distance

Heap

E 3
D 5
2

5
3

1
1

A
1

E 3

C
4

Heap

D 5
2

5
3

1
1

A
1

E 3

C
4

Heap

5
3

1
1

A
1

E 3

C
4

Heap

1
1

A
1

E 3

Is Dijkstras algorithm correct?

Invariant:

Is Dijkstras algorithm correct?

Invariant: For every vertex removed from the heap,


dist[v] is the actual shortest distance from s to v

Running time?

Running time?

1 call to MakeHeap

Running time?

|V| iterations

Running time?

|V| calls

Running time?

O(|E|) calls

Running time?

Depends on the heap implementation


1 MakeHeap

|V| ExtractMin

|E| DecreaseKey

Array

O(|V|)

O(|V|2)

O(|E|)

Bin heap

O(|V|)

O(|V| log |V|)

O(|E| log |V|)

Total
O(|V|2)

O((|V|+|E|) log |V|)


O(|E| log |V|)

Running time?

Depends on the heap implementation


1 MakeHeap

|V| ExtractMin

|E| DecreaseKey

Array

O(|V|)

O(|V|2)

O(|E|)

Bin heap

O(|V|)

O(|V| log |V|)

O(|E| log |V|)

Total
O(|V|2)

O((|V|+|E|) log |V|)


O(|E| log |V|)

Is this an improvement?

If |E| < |V|2 / log |V|

Running time?

Depends on the heap implementation


1 MakeHeap

|V| ExtractMin

|E| DecreaseKey

Array

O(|V|)

O(|V|2)

O(|E|)

Bin heap

O(|V|)

O(|V| log |V|)

O(|E| log |V|)

Total
O(|V|2)

O((|V|+|E|) log |V|)


O(|E| log |V|)

Fib heap

O(|V|)

O(|V| log |V|)

O(|E|)

O(|V| log |V| + |E|)

What about Dijkstras on?

D
5

10

-10

What about Dijkstras on?

D
5

10

-10

What about Dijkstras on?


Dijkstras algorithm only works
for positive edge weights
1

D
5

10

You might also like