lecture 14 - university at buffalo

Post on 22-Apr-2022

2 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Lecture 14

CSE 331Mar 3, 2021

Due this Friday 8:00pm!

Only 165 (of 271) students submitted!

Use CC[v] array

Lj+1 set of vertices not chosen yet but are connected to Lj

Use linked lists

Breadth First Search (BFS)

Build layers of vertices connected to s

L0 = {s}

Assume L0,..,Lj have been constructed

Stop when new layer is empty

Rest of Today’s agenda

Quick run time analysis for BFS

Helping you schedule your activities for the day

Quick run time analysis for DFS (and Queue version of BFS)

O(m+n) BFS Implementation

BFS(s)

CC[s] = T and CC[w] = F for every w≠ s

Set i = 0Set L0= {s}

While Li is not empty

Li+1 = Ø

For every u in Li

For every edge (u,w)

If CC[w] = F then

CC[w] = T

Add w to Li+1

i++

Array

Linked List

Input graph as Adjacency list

Version in KT also

computes a BFS tree

All the layers as one

BFS(s)

CC[s] = T and CC[w] = F for every w≠ s

Set i = 0

Set L0= {s}

While Li is not empty

Li+1 = Ø

For every u in Li

For every edge (u,w)

If CC[w] = F then

CC[w] = T

Add w to Li+1

i++

All layers are

considered in first-

in-first-out order

Can combine all layers

into one queue: all the

children of a node are

added to the end of the

queue

An illustration

1

2 3

4 5

6

7

8

1 2 3 4 5 7 8 6

Queue O(m+n) implementation

BFS(s)

CC[s] = T and CC[w] = F for every w≠ s

Intitialize Q= {s}

While Q is not empty

Delete the front element u in Q

For every edge (u,w)

If CC[w] = F then

CC[w] = T

Add w to the back of Q

O(n)

O(1)

O(1)

Repeated nu times

O(nu)

Repeated at most once for each

vertex u

Σu O(nu) = O(Σu nu) =

O(m) O(1)

Questions?

Implementing DFS in O(m+n) time

Same as BFS except stack instead of a queue

A DFS run using an explicit stack

1

2 3

4 5

6

7

8

1

2

4

5

3

8

6

7

1 2 4 5 36 87

DFS stack implementation

DFS(s)

CC[s] = T and CC[w] = F for every w≠ s

Intitialize Ŝ = {s}

While Ŝ is not empty

Pop the top element u in Ŝ

For every edge (u,w)

If CC[w] = F then

CC[w] = T

Push w to the top of Ŝ

Same O(m+n) run

time analysis as for BFS

Questions?

Reading AssignmentSec 3.3, 3.4, 3.5 and 3.6 of [KT]

Directed graphs

Model asymmetric relationships

Precedence relationships

u needs to be done before w means (u,w) edge

Directed graphsAdjacency

matrix is not symmetric

Each vertex has two lists in Adj. list rep.

Directed Acyclic Graph (DAG)

No directed cycles

Precedence relationships are

consistent

Topological Sorting of a DAG

Order the vertices so that all edges go “forward”

More details on Topological sort

Questions?

top related