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

Graph Lecture (1)

The document provides an overview of graphs, including their definitions, types, terminologies, and representations. It covers concepts such as directed and undirected graphs, weighted and unweighted graphs, and discusses various graph algorithms and problem-solving approaches. Additionally, it includes code examples for implementing graph structures and highlights common pitfalls in graph-related problems.

Uploaded by

tewobstal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Graph Lecture (1)

The document provides an overview of graphs, including their definitions, types, terminologies, and representations. It covers concepts such as directed and undirected graphs, weighted and unweighted graphs, and discusses various graph algorithms and problem-solving approaches. Additionally, it includes code examples for implementing graph structures and highlights common pitfalls in graph-related problems.

Uploaded by

tewobstal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

Graphs

Lecture Flow

1) Definition of Graphs
2) Types of Graphs
3) Graph terminologies
4) Graph representations
5) Graphs & Trees
6) Receiving Inputs on Graph Problems
7) Practice questions

2
What is a 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?


Unweighted Graph
● All edges have the same value
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
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
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?
Disadvantages:
Advantages:
● Edge look up is slow
● It uses less memory.
● Hard to traverse
● Easy to represent
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
int main() {
int n;
cin >> n;
vector<vector<pair<int,int>>> graph(n);

for(int i = 0; i < n; ++i) {


string line;
getline(cin >> ws, line); // read full row
istringstream iss(line);
for(int j = 0, x; iss >> x; ++j) // parse each int
graph[i].emplace_back(j, x); // store (column, value)
}

return 0;
}
Complexity Analysis
Time Complexity: O(n^2) Space
Complexity: O(n^2)

n = number of nodes(matrix length)


On Undirected Weighted Graphs
Code
int main() {
int n;
cin >> n;
vector<vector<pair<int,int>>> graph(n);
for (int i = 0; i < n; ++i) {
// read one full row of n integers
vector<int> row(n);
for (int j = 0; j < n; ++j)
cin >> row[j];

for (int j = 0; j < n; ++j) {


graph[i].emplace_back(j, row[j]);
graph[j].emplace_back(i, row[i]);
}
}

return 0;
}
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
int main() {
int n;
cin >> n;
unordered_map<int, vector<pair<int,int>>> graph;

for (int i = 0; i < n; ++i) {


int src, dest, w;
cin >> src >> dest >> w;
graph[src].emplace_back(dest, w);
}

return 0;
}
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(n)

n = number of edges
Adjacency List Inputs
For Undirected Unweighted Graph
Think of ways to implement this
On Directed Weighted Graph
int main() {
int n;
cin >> n;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
unordered_map<int, vector<pair<int,int>>> graph;
for (int i = 0; i < n; ++i) {
string line;
getline(cin, line);
istringstream iss(line);
int node;
iss >> node; // first token is the node ID
string token;
// remaining tokens are "adj_node,weight"
while (iss >> token) {
auto pos = token.find(',');
int adj = stoi(token.substr(0, pos));
int w = stoi(token.substr(pos + 1));
graph[node].emplace_back(adj, w);
}
}
return 0;
}
Complexity Analysis
Time Complexity: O(n+m)
Space Complexity: O(2m)

n = number of nodes
m = number of edges
Common Pitfalls
Common Pitfalls
● Not considering cycles in the graph.

● Not checking whether the graph is directed or undirected

● Not understanding input format well

● Falling in to infinite loop (because of cycles)


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.


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
Leetcode Question

Find if Path Exist


Find Center of Star Graph
All path from source to target

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy