0% found this document useful (0 votes)
35 views

A2SV Graph Lecture

Graphs are a way to represent relationships between objects using nodes connected by edges. Common graph terminology includes nodes, edges, paths, cycles, connectivity, and components. Graphs can be represented using adjacency matrices, adjacency lists, and edge lists. Common graph algorithms include depth-first search, breadth-first search, Dijkstra's algorithm, and topological sorting.

Uploaded by

fedasa.bote
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

A2SV Graph Lecture

Graphs are a way to represent relationships between objects using nodes connected by edges. Common graph terminology includes nodes, edges, paths, cycles, connectivity, and components. Graphs can be represented using adjacency matrices, adjacency lists, and edge lists. Common graph algorithms include depth-first search, breadth-first search, Dijkstra's algorithm, and topological sorting.

Uploaded by

fedasa.bote
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 83

Graphs

What is graph?
Definition
● A way to represent relationships between objects.
● A collection of nodes that have data and are connected to other
nodes.
Example: Friendship Graph

● Nodes or vertices:
The objects in graph
○ These people
our case
● Edges: the relation
between nodes.
○ The friendship
between them
(the lines)
What are the types of graphs?
Undirected Graph
● Facebook friendship

● If Alice is friends with Bob, Bob


is also friends with alice
Directed Graph
● Twitter's "following" relation

● If person A follows person B,

that does not mean that


person B follows person A.
Let’s say we want to add a weight parameter which
represents the strength of the friendship.

How can we do that?


Weighted Graph
● Weighted graphs assign

numerical values to edges.


Graph Terminologies
Node / vertex
● Represent entities (e.g., people, devices).

● Connected to other nodes by edges.


Edge
● Connection between two nodes.

● Represented by lines or arrows.

● model relationships in various systems.


Neighbors
Two nodes are neighbors or adjacent if there is an edge between them
Degree of graph
● Node degree = number of
neighbors.

● In directed graphs:

○ Indegree = edges
ending at node.

○ Outdegree = edges
starting at node.
Path
● A path leads from one node to another.

● The length of a path is the number of edges in it.

● Let’s consider the path between node A and node F


Do you see another path?
Cycle

A path is a cycle if the first and the last node of the path is the same.
Connectivity
● A graph is connected if there is a path between any two nodes
Components
The connected parts of a graph are called its components
Complete Graph
A complete graph is a graph in which each pair of node is connected by an edge.
Summary
Common Terminologies
Node: _____?

Edge: _____?

Path: _____?

Cycle: _____?

Connectivity: _____?

Components: _____?
Common Terminologies
Node: represents elements

Edge: is like a line connecting two points or nodes

Path: list of edges that connects nodes

Cycle: if start and end of a path is the same

Connectivity: if there is a path between any two nodes of the graph

Components: connected part of a graph


Common Terminologies
Tree: _____?

Neighbours(adjacent): _____?

Degree: _____?

Indegree: _____?

Outdegree: _____?

Complete Graph: _____?

Traverse: _____?
Common Terminologies
Tree: is a connected graph consists of n nodes and n-1 edges

Neighbours(adjacent): two nodes are neighbors if there is an edge between them

Degree: is number of neighbours a node has

Indegree: number of edges that ends at the node

Outdegree: number of edges that starts at the node

Complete Graph: every node has n-1 degree(an edge from every node to every other node)

Traverse: going through the graph using edges


Different ways of representing graphs
Graph Representation
● Adjacency Matrix

● Adjacency List

● Edge List

● Grids as Graphs
Adjacency matrix
Advantages and disadvantages of
adjacency matrix?
Advantages: Disadvantage:

● To represent dense graphs. ● It takes more memory (O(N**2))

● Finding neighbors of a node is costly


Adjacency list using list
Adjacency list using linked list
Advantages and disadvantages of
Adjacency List?
Advantages: Disadvantages:

● It uses less memory. ● Edge look up is slow

● Best for sparse graphs


Edge List
Advantages and disadvantages of
Edge List?
Advantages: Disadvantages:

● It uses less memory. ● Edge look up is slow

● Easy to represent ● Hard to traverse


Grids as Graph
● Matrix cells = nodes

● Edges between adjacent cells:

○ 4 perpendicular

○ 2 diagonal/antidiagonal.
Direction vectors
Graph and Tree
Tree
● A tree is a connected and acyclic graph.
● A tree has a unique path between any two vertices.
● How many edges does a tree have?
Receiving Inputs on Graph Problems
Adjacency Matrix Inputs
On Directed Weighted Graphs
Code
from collections import defaultdict

n = int(input())
graph = defaultdict(list)
for i in range(n):
row = list(map(int, input().split()))

for j in range(len(row)):
graph[i].append((j, row[j]))
Complexity Analysis
Time Complexity: O(n^2)
Space Complexity: O(n^2)

n = number of nodes(matrix length)


On Undirected Weighted Graphs
Code
from collections import defaultdict

n = int(input())
graph = defaultdict(list)
for i in range(n):
row = list(map(int, input().split()))

for j in range(len(row)):
graph[i].append((j, row[j]))
graph[j].append((i, row[i]))
Complexity Analysis
Time Complexity: O(n^2)
Space Complexity: O(n^2)

n = number of nodes(matrix length)


Edge List Inputs
Edge List Input on Directed Weighted Graphs
Code
from collections import defaultdict

n = int(input())
graph = defaultdict(list)
for i in range(n):
Src, dest, w = list(map(int, input().split()))

Graph[src].append((dest, w))
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(2n)

n = number of edges
Another Form of Edges List
Adjacency List Inputs
On Directed Weighted Graph
Code
from collections import defaultdict

n = int(input())
graph = defaultdict(list)

for i in range(n):
line = input().split()
node = int(line[0])

for neighbor in range(1, len(line)):


adj_node, weight = map(int, line[neighbor].split(","))

graph[node].append((adj_node, weight))
Complexity Analysis
Time Complexity: O(n+m)
Space Complexity: O(2m)

n = number of nodes
m = number of edges
For Multiple Graph Problems
Which kind of input is the graph?
OR
To make your inputs faster…

This replaces the input() function with sys.stdin.readline() which is


faster.

Why is it faster? (Question for the graph lecturers)


Common Pitfalls
Common Pitfalls
● Not considering cycles in the graph.

● Not checking whether the graph in directed or not

● Not understanding input format well

● Falling in to infinite loop with taking visited


Types of Graph Questions
● Graph questions can be classified into different categories based on
the problem requirements.

● Some common types of graph questions include:

● Shortest path: find the shortest path between two vertices.

● Connectivity: determine if there is a path between two vertices.

● Cycle detection: detect cycles in the graph.

● Topological sorting: order the vertices in a directed acyclic graph.


Approaches to Solving Graph Problems
● There are several approaches to solving graph problems, including:

● Breadth-first search (BFS)

● Depth-first search (DFS)

● Dijkstra's algorithm

● Bellman-Ford algorithm

● Kruskal's algorithm

● Floyd-Warshall algorithm

The choice of algorithm depends on the problem requirements.


What is next?
Graph Traversal: DFS and BFS
Shortest path: Dijkstra
Shortest path: Bellman Ford
Topological Sort
Exercise problems…

1. Operations on graph
2. Cities and roads
3. From adjacency matrix to adjacency list

4. From adjacency list to adjacency matrix

5. Regular graph
6. Sources and sinks
For more graph representation Problems: Link
Quote of the day
“Slow Success builds character.
Fast Success builds ego.”
~ Unknown

You might also like