Docsity

Graph Theory: Breadth-First Search and Depth-First Search Algorithms - Prof. Nelson Padua-, Study notes of Computer Science

Partial preview of the text

Download Graph Theory: Breadth-First Search and Depth-First Search Algorithms - Prof. Nelson Padua- and more Study notes Computer Science in PDF only on Docsity!

Graphs & Graph Algorithms

CMSC 132

Department of Computer ScienceUniversity of Maryland, College Park

Overview

Graph Data Structures Graph Definitions Graph Operations Breadth-first Search (BFS) Traversals Orders Depth-first Search (DFS) Traversal Algorithms BFS vs. DFS Traversal

Graph Definitions

Node

Element of graph State

List of adjacent nodes Edge

Connection between two nodes State

Endpoints of edge

A

Graph Definitions

Directed graph

Directed edges Undirected graph

Undirected edges

Graph Definitions

Path

Sequence of nodes n

, n 1

, … n 2

k

Edge exists between each pair of nodes n

, ni i+

Example

A, B, C

is a path

Graph Definitions

Path

Sequence of nodes n

, n 1

, … n 2

k

Edge exists between each pair of nodes n

, ni i+

Example

A, B, C

is a path A, E, D

is not a path

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 nodefirst View as series ofexpanding circles Keep list of nodes to visitin queue Example traversal

n a, c, b e, g, h, i, j d, f

Breadth-first Search (BFS)

Example traversals starting from 1

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 ina stack Example traversal

n, a, b, c, d, … f …

Depth-first Search (DFS)

Example traversals from 1

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 }

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