Graphs – Adjacency Matrix • Graph with N vertices: Nx. N adjacency matrix • A[i][j] = 1 if vertex i is adjacent to vertex j; 0 otherwise A B E C D A B C A 0 1 1 B 1 0 0 C 1 0 0 D 1 0 1 E 0 1 0 D E 1 0 0 1 1 0 0 0 COSC 2 P 03 Week 8 1
Graphs – Adjacency List • Array of linked lists • If vertex i is adjacent to vertex j then: – j is in the adjacency list for i and – i is in the adjacency list for j A B E C D A B C D → → E → B COSC 2 P 03 Week 8 B A A A → → C → D E D C 2
Directed Graphs • Adjacency matrix: A[i][j]=1 iff there is an edge from i to j (else A[i][j]=0) • Adjacency list: j is in list i iff there is an edge from i to j A B C D E F A 0 1 0 0 B 0 0 1 0 C 1 0 0 1 0 D 1 0 0 0 E 0 0 0 F 0 0 0 A B E C D F A → B B → E 0 C → A D → A 0 0 E → D 1 0 1 F → D 1 0 0 COSC 2 P 03 Week 8 → D → F 3
Depth-first Search Suppose that our starting vertex is v. DFS(v) { v. was. Visited = true; while there is an unvisited vertex u adjacent to v { DFS(u); } } Exercise: Think about how to do this with an iterative method COSC 2 P 03 Week 8 4
Breadth-first Search • • We need a queue Q that stores vertices. Suppose that our starting vertex is v. was. Visited = true; Q. enqueue(v); while !Q. is. Empty() // loop 1 { v = Q. dequeue(); while there is an unvisited vertex u adjacent to v // loop 2 { u. was. Visited = true; Q. enqueue(u); } } COSC 2 P 03 Week 8 5