Docsity

Graph and Traversal - Object Oriented Programming II | CMSC 132, Study notes of Computer Science

Partial preview of the text

Download Graph and Traversal - Object Oriented Programming II | CMSC 132 and more Study notes Computer Science in PDF only on Docsity!

CMSC 132:

Object-Oriented Programming II

Graphs & Graph Traversal

Department of Computer Science University of Maryland, College Park

Graph Data Structures

Many-to-many relationship between elements Each element has multiple predecessors Each element has multiple successors

Graph Definitions

Directed graph Directed edges Undirected graph Undirected edges

Graph Definitions

Weighted graph Weight (cost) associated with each edge

Graph Definitions

Cycle Path that ends back at starting node Example A, E, A A, B, C, D, E, A Simple path No cycles in path Acyclic graph No cycles in graph

Graph Definitions

Reachable Path exists between nodes Connected graph Every node is reachable from some node in graph Unconnected graphs

Breadth-first Search (BFS)

Approach Visit all neighbors of node first View as series of expanding circles Keep list of nodes to visit in queue Example traversal

  1. n
  2. a, c, b
  3. e, g, h, i, j
  4. d, f

Breadth-first Tree Traversal

Example traversals starting from 1 1 2 3 4 5 6 7

Left to right Right to left Random

Depth-first Search (DFS)

Approach Visit all nodes on path first Backtrack when path ends Keep list of nodes to visit in a stack Example traversal

  1. N
  2. A
  3. B, C, D, …
  4. F…

Depth-first Tree Traversal

Example traversals from 1 (preorder) 1 2 6 3 5 7 4

Left to right Right to left Random

Traversal – Avoid Revisiting Nodes

Record set of visited nodes Initialize { Visited } to empty set Add to { Visited } as nodes is visited Skip nodes already in { Visited } 1 2 3 4 V = ∅

V = { 1 }

V = { 1, 2 }

Traversal – Avoid Revisiting Nodes

Mark nodes as visited Initialize tag on all nodes (to False) Set tag (to True) as node is visited Skip nodes with tag = True F F F F

T

F F

F

T

T F

F

Traversal Algorithm Using Tags

for all nodes X set X.tag = False { Discovered } = { 1st node } while ( { Discovered } ≠ ∅ ) take node X out of { Discovered } if (X.tag = False) set X.tag = True for each successor Y of X if (Y.tag = False) add Y to { Discovered }

BFS vs. DFS Traversal

Order nodes taken out of { Discovered } key Implement { Discovered } as Queue First in, first out Traverse nodes breadth first Implement { Discovered } as Stack First in, last out Traverse nodes depth first