Text

@BiancaGando

# Graphs

## Concept

Graphs are a set of vertices connected by edges

Each item in the graph contains:

1. Stored data -- aka node value
2. Stored references -- aka relationships aka edges -- to zero or more other nodes

@BiancaGando

## Vocabulary

@BiancaGando

Edges

represent the connection b/t 2 vertices

can be directed or undirected

Vertices

nodes in the graph

Path

a sequence of connected vertices

a simple path has no repeated vertices

Cycles

a path that is cyclical

an acyclic graph has no cycles

Text

@BiancaGando

Deleting an edge

Detecting an edge

Finding the neighbors of a vertex

Finding a path between two vertices

@BiancaGando

# Graphs

Text

@BiancaGando

Undirect Graph

Text

@BiancaGando

Directed Graph

@BiancaGando

Weighted Directed Graph

@BiancaGando

## Pseudocode

Constructor

addEdge()

@BiancaGando

Directed Graph

@BiancaGando

## Pseudocode

Constructor

addEdge()

Consider:

How could we represent (un)directed edges?

How could we represent weighted edges?

@BiancaGando

Text

@BiancaGando

# DFS

@BiancaGando

Why? Find paths, cycles, connectivity and more!

Concepts:

Explored (black), Visited (gray), Undiscovered (white)

@BiancaGando

## Pseudocode

//Code here

# Exercise Time!

@BiancaGando

@BiancaGando

1. Mark v as discovered (grey).

2. For all unvisited (white) neighbors w of v:

1. Visit vertex w.

3. Mark v as explored (black).

## Procedure

O(n)
$O(n)$

Text

@BiancaGando

# BFS

@BiancaGando

@BiancaGando

@BiancaGando

## Pseudocode

//Code here

@BiancaGando

1. Create a queue Q.

2. Mark v as discovered (grey) and enqueue v into Q.

3. While Q is not empty, perform the following steps:

1. Dequeue u from Q.

2. Mark u as discovered (grey).

3. Enqueue all unvisited (white) neighbors w of u.

4. Mark u as explored (black).

## Procedure

@BiancaGando

1. BFS Function

- queue

- recursion

2. Tree vs Graph Data Structure

@BiancaGando

O(n)

## Time Complexity

@BiancaGando

Shortest path finding

Web crawlers

@BiancaGando

# Recap

• DFS and BFS can be applied to graphs and trees
• information about how data is organized in the graph or tree can aid in determining whether to use DFS or BFS
• BFS can be implemented using helper data structures
• DFS can be implemented recursively and is the simpler of the two methods to implement

# Exercise Time!

@BiancaGando

#### Graphs & Paths

By Bianca Gandolfo

• 2,040