✅ 1. What is a Graph?
A Graph is a collection of:
-
Vertices (nodes) – Represent entities
-
Edges (connections) – Represent relationships between vertices
Graphs can be:
-
Directed or Undirected
-
Weighted or Unweighted
-
Cyclic or Acyclic
✅ Types of Graphs in Data Structures
Graphs can be classified based on direction, weight, connectivity, cycles, and completeness:
🔹 1. Directed Graph (Digraph)
-
Edges have a direction (from one vertex to another).
-
Represented as ordered pairs (A → B).
🧠 Use-case: Web page links, road maps with one-way streets.
🔹 2. Undirected Graph
-
Edges have no direction.
-
Represented as unordered pairs (A — B).
🧠 Use-case: Social networks (mutual friendships), electrical circuits.
🔹 3. Weighted Graph
-
Each edge has a weight or cost (e.g., distance, time, cost).
-
Can be directed or undirected.
🧠 Use-case: Google Maps (shortest route), network latency.
🔹 4. Unweighted Graph
-
No weights on edges.
-
Just shows connections.
🧠 Use-case: Graphs for basic structure or logic.
🔹 5. Cyclic Graph
-
Contains at least one cycle.
-
A cycle is a path that starts and ends at the same vertex.
🧠 Use-case: Circular dependencies in systems.
🔹 6. Acyclic Graph
-
Contains no cycles.
-
If directed and acyclic → DAG (Directed Acyclic Graph).
🧠 Use-case: Task scheduling, dependency resolution, Git commits.
🔹 7. Connected Graph
-
Every vertex is reachable from every other vertex (in undirected graph).
🧠 Use-case: LAN networks, team communication.
🔹 8. Disconnected Graph
-
Some vertices are not connected.
-
Has two or more separate components.
🧠 Use-case: Incomplete systems, unconnected subnetworks.
🔹 9. Complete Graph
-
Each vertex is connected to every other vertex.
-
For
n
vertices →n(n-1)/2
edges (undirected).
🧠 Use-case: Dense networks, test cases in algorithms.
🔹 10. Sparse Graph
-
Few edges compared to the number of vertices.
-
E.g., Tree or Linked List structure.
🔹 11. Dense Graph
-
Many edges, close to complete graph.
-
May include loops or multiple edges.
🔹 12. Multigraph
-
Can have multiple edges (parallel edges) between the same pair of vertices.
🧠 Use-case: Transportation routes with multiple options.
🔹 13. Subgraph
-
A portion of a graph formed using some of its vertices and edges.
🔹 14. Tree (a special graph)
-
A connected, acyclic, undirected graph.
-
Has
n-1
edges forn
vertices.
🧠 Use-case: Hierarchies, file systems.
🧠 Summary Table:
Type | Directed? | Weighted? | Cycles? | Connected? |
---|---|---|---|---|
Directed Graph | ✅ | ❌/✅ | ❌/✅ | ❌/✅ |
Undirected Graph | ❌ | ❌/✅ | ❌/✅ | ❌/✅ |
Weighted Graph | ❌/✅ | ✅ | ❌/✅ | ❌/✅ |
Acyclic Graph | ❌/✅ | ❌/✅ | ❌ | ✅/❌ |
Complete Graph | ❌ | ❌/✅ | ✅ | ✅ |
Tree | ❌ | ❌/✅ | ❌ | ✅ |
✅ Basic Graph Terminologies
Term | Meaning |
---|---|
Graph (G) | A collection of vertices (nodes) and edges (connections). |
Vertex (Node) | A point in the graph (like a city, person, etc.). |
Edge | A connection between two vertices. |
Adjacent | Two vertices are adjacent if there is an edge between them. |
Degree | Number of edges connected to a vertex. |
Directed Edge | Edge that has a direction (from one vertex to another). |
Undirected Edge | Edge without direction (mutual connection). |
Weighted Edge | An edge with a cost or weight (e.g., distance, time). |
Path | A sequence of vertices where each adjacent pair is connected by an edge. |
Cycle | A path that starts and ends at the same vertex. |
Acyclic Graph | A graph with no cycles. |
Connected Graph | Every vertex is reachable from any other vertex. |
Disconnected Graph | At least one vertex is not reachable from others. |
Complete Graph | Each vertex is connected to every other vertex. |
Subgraph | A smaller part (subset of nodes/edges) of a graph. |
Sparse Graph | A graph with few edges compared to the number of vertices. |
Dense Graph | A graph with many edges, close to complete. |
Multigraph | A graph where multiple edges can exist between two vertices. |
Self-loop | An edge that connects a vertex to itself. |
✅ Additional Terminologies for Advanced Graphs
Term | Meaning |
---|---|
Directed Graph (Digraph) | Graph where all edges have direction. |
Undirected Graph | Graph where edges have no direction. |
DAG (Directed Acyclic Graph) | A directed graph with no cycles. |
Tree | A connected, acyclic, undirected graph. |
Rooted Tree | A tree with a root node from where traversal starts. |
Traversal | Visiting all vertices/nodes (e.g., BFS, DFS). |
Bridge | An edge whose removal increases the number of connected components. |
Articulation Point | A vertex whose removal disconnects the graph. |
Isolated Vertex | A node not connected to any other node. |
Component | A maximally connected subgraph. |
🧠 Graph Implementations in Python – Definitions
-
Adjacency List
A dictionary where each key is a node, and its value is a list (or set) of adjacent nodes.
✅ Memory-efficient for sparse graphs.
✅ Easy to iterate over neighbors.
❌ Slower edge lookup: O(n) time (if using list).
Example:
-
Adjacency Matrix
A 2D matrix (list of lists) where
matrix[i][j] = 1
if there is an edge from node i to j.✅ Fast edge lookup: O(1).
❌ Consumes more memory (O(n²)) even for sparse graphs.
Example:
-
Dictionary of Sets or Lists
A variation of adjacency list where each node points to a set or list.
✅ Sets offer faster lookup (O(1)) than lists (O(n)).
✅ Prevents duplicate edges.
❌ Sets are unordered, which may be less intuitive for traversals.
Example using sets:
🎯 Diagram: Comparison
✅ Summary Table
Feature | Adjacency List | Adjacency Matrix | Dictionary of Sets |
---|---|---|---|
Space Efficient | ✅ Yes | ❌ No (O(n²)) | ✅ Yes |
Fast Neighbor Lookup | ✅ Yes | ❌ No | ✅ Yes |
Fast Edge Lookup | ❌ No (O(n)) | ✅ Yes (O(1)) | ✅ Yes (O(1)) |
Prevents Duplicates | ❌ No | ✅ Yes | ✅ Yes |
🔧 Basic Graph Operations (using Adjacency List method):
We'll implement:
-
Add Vertex (Node)
-
Add Edge
-
Remove Vertex
-
Remove Edge
-
Check for Edge
-
Display Graph
-
Traverse Graph (BFS and DFS)
⚙️ 1. Create a Graph Class
👉 We start with an empty dictionary to store our graph.
➕ 2. Add Vertex
✅ Explanation: If the vertex is not already in the graph, we add it with an empty list (no connections yet).
🔗 3. Add Edge (Undirected)
✅ Explanation:
-
Adds an edge between
v1
andv2
. -
Since it's undirected, we add both ways (v1 → v2 and v2 → v1).
❌ 4. Remove Vertex
✅ Explanation:
-
Removes the vertex.
-
Also removes it from every other vertex's neighbor list.
✂️ 5. Remove Edge
✅ Explanation: Deletes the connection from both nodes.
🔍 6. Check for Edge
✅ Explanation: Returns True if there is a direct edge from v1
to v2
.
📤 7. Display Graph
✅ Explanation: Prints the full graph in an easy-to-read format.
🔄 8. Graph Traversals
A. BFS (Breadth-First Search)
✅ Explanation:
-
Visits level by level.
-
Uses queue (FIFO).
-
Good for finding shortest path.
B. DFS (Depth-First Search)
✅ Explanation:
-
Visits as deep as possible before backtracking.
-
Uses recursion (or stack).
-
Good for exploring all paths.
✅ Full Example
📌 Output:
📝 Summary Table
Operation | Tool Used | Time Complexity |
---|---|---|
Add Vertex | Dictionary | O(1) |
Add Edge | List Append | O(1) |
Remove Vertex | List Remove | O(V) |
Remove Edge | List Remove | O(E) |
Has Edge | List Lookup | O(E) |
Display | O(V + E) | |
BFS Traversal | Queue | O(V + E) |
DFS Traversal | Recursion/Stack | O(V + E) |
🎨Basic Graph Operations
![]() |
Insert Vertex |
📌 1. Insert Vertex (Add Vertex)
🧠 Definition:
To add a new node to the graph that does not have any edges yet.
✅ Example:
Let’s add a vertex ‘D’ to this graph:
Before:
After adding ‘D’:
➡ ‘D’ is added but has no connections yet.
❌ 2. Delete Vertex (Remove Vertex)
🧠 Definition:
To remove a vertex from the graph and all edges connected to it.
✅ Example:
Delete vertex ‘B’ from this graph:
Before:
After deleting ‘B’:
➡ Node B and edge A–B are removed.
🔗 3. Insert Edge (Add Edge)
🧠 Definition:
To add a connection (edge) between two existing vertices.
✅ Example:
Add an edge between ‘B’ and ‘C’:
Before:
After adding edge B–C:
➡ ‘B’ and ‘C’ are now connected.
✂️ 4. Delete Edge (Remove Edge)
🧠 Definition:
To remove a connection (edge) between two existing vertices without deleting the vertices.
✅ Example:
Delete edge between A and B:
Before:
After deleting edge A–B:
➡ ‘A’ and ‘B’ are now not connected, but both still exist.
🖼️ Combined Mini Diagrams
Operation | Diagram Before | Operation | Diagram After |
---|---|---|---|
Insert Vertex | A---B | C | Add D | A---B | D C |
Delete Vertex | A---B | C | Remove B | A | C |
Insert Edge | A---B C | Add B–C | A---B---C |
Delete Edge | A---B | C | Remove A–B | A B | C |
![]() |
Diagram of Operations |
🌐 Graph Traversal Algorithms
Graph traversal means visiting every node in a graph in a systematic way.
The two main traversal methods are:
-
BFS (Breadth-First Search)
-
DFS (Depth-First Search)
We'll cover both with diagrams, Python code, and explanation.
🔄 1. Breadth-First Search (BFS)
📌 Definition:
-
Visits level by level
-
Uses queue (FIFO)
-
Best for finding shortest paths in unweighted graphs
✅ Python Code:
✅ Graph Example:
🔍 Output:
🧠 Code Explanation:
-
visited
: Keeps track of visited nodes -
queue
: Holds nodes to explore (FIFO) -
while loop
: Runs until queue is empty -
queue.popleft()
: Gets next node to visit -
visited.add()
: Marks it as visited -
queue.extend()
: Adds unvisited neighbors to the queue
🔁 2. Depth-First Search (DFS)
📌 Definition:
-
Visits as deep as possible before backtracking
-
Uses stack or recursion
-
Good for path finding and cycle detection
✅ Python Code (Recursive):
✅ Graph Example:
🔍 Output:
🧠 Code Explanation:
-
visited
: Keeps track of visited nodes -
Starts from node ‘A’
-
Goes to B → D → E → F → C
-
Uses recursive calls to go deeper
📊 BFS vs DFS Comparison
Feature | BFS | DFS |
---|---|---|
Data Structure | Queue (FIFO) | Stack (via recursion or list) |
Visit Order | Level-by-Level | Deep First, then backtrack |
Finds Shortest Path | ✅ Yes | ❌ No |
Good For | Shortest path, Web crawlers | Maze solving, Topological sort |
Time Complexity | O(V + E) | O(V + E) |
-
V = number of vertices
-
E = number of edges
✅ Summary
-
Use BFS when you need the shortest path or work level-wise.
-
Use DFS when you want to go deep into paths or solve backtracking problems.
No comments:
Post a Comment