SENG 313 Graphs Algorithm - PART1
SENG 313 Graphs Algorithm - PART1
Algorithm Analysis
Graph Algoritms
Topics
1. Graph Representation
2. Traversals (BFS and DFS)
3. Shortest Path Algorithms
4. Minimum Spanning Trees
5. Advanced Graph Algorithms
6. Real-World Applications
Why Study Graph Algorithms?
• Definition:
• Vertex (Node): Fundamental unit of a graph (e.g.,
people, cities).
• Edge (Connection): Link between two vertices (e.g.,
friendships, roads).
• Types of Graphs:
• Directed vs. Undirected.
• Weighted vs. Unweighted.
• Example:
A graph with three nodes (A, B, C) connected by
edges, with one edge weighted.
Applications of Graphs
Python Code Example: Modeling a Social Network
Graph Representation Overview
Definition: A graph can be represented in multiple ways to make algorithms efficient for specific use cases.
•Primary Types:
•Trade-Offs:
•Space complexity.
•Time complexity for edge queries and traversal.
•Why Representation Matters: Choosing the right representation can significantly affect algorithm efficiency.
Adjacency Matrix
What Is It?
• A square matrix of size V×V (where V is the number of vertices).
• If there’s an edge between vertex i and vertex j, matrix[i][j] = 1 (or weight for weighted graphs).
Otherwise, it’s 0.
• 1 (or the weight of the edge) means an edge exists.
• 0 means no edge exists.
Adjacency Matrix
Advantages
• Edge Query Time O(1): Checking if there's an edge between i
and j is instantaneous (matrix lookup).
• Simpler Implementation: Easy to code and use for dense
graphs.
Disadvantages
• Space Complexity O(V^2): Even for sparse graphs with very few
edges, we allocate memory for all possible connections.
• Traversal Complexity: Traversing all edges requires scanning
the entire matrix (O(V^2)).
Real-World Analogy
• Think of an adjacency matrix as a city map grid, where every
intersection (vertex) and every road (edge) is explicitly
represented, even if most intersections are unconnected.
Adjacency List
What Is It?
• An adjacency list is a collection of lists or dictionaries, where each vertex i has a list of its
neighboring vertices.
Adjacency Matrix Adjacency List
Adjacency List
Each key represents a vertex, and the list represents all vertices it is connected to:
• Vertex 0 connects to vertices 1 and 3.
• Vertex 1 connects to vertices 2 and 4.
Adjacency Matrix Adjacency List
Adjacency List
Advantages
• Space Efficiency O(V+E): Only stores edges that exist, making it ideal
for sparse graphs.
• Traversal Efficiency: Traversing all neighbours of a vertex is quick (O(k),
where k is the number of neighbours).
Disadvantages
• Edge Query Time O(k): Checking if an edge exists may require scanning
the list of neighbours.
Real-World Analogy
• Think of an adjacency list as a contact list: you only store actual
connections (edges), not every possible combination.
Comparison of Adjacency Matrix and Adjacency
List
• Objective:
• Discover the structure of the graph.
• Explore connections and paths.
• Solve problems like connectivity, pathfinding, and cycles.
• Key Concept:
• Traversals systematically visit all vertices and edges.
• Real-World Analogy:
• BFS is like casting a wide net (spreading news to neighbors first).
• DFS is like digging deep (exploring one path to the end before backtracking).
Breadth-First Search (BFS)
• Algorithm:
• Start from a source node.
• Explore all its neighbors, then move to their neighbors.
• Use a queue to manage the nodes to visit next.
• Steps:
• Enqueue the starting node.
• Dequeue a node, mark it as visited, and enqueue all its unvisited neighbors.
• Repeat until the queue is empty.
Breadth-First Search (BFS)
• Time Complexity: O(V+E), where V is vertices, and E is edges.
• Space Complexity: O(V) for the queue.
• Example Graph:
• Nodes: A, B, C, D, E
• BFS from A: Visit order: A → B → C → D → E
Concept Overview
•BFS explores a graph level by level, starting from a given node
(source) and visiting all its neighbors before moving to their
neighbors.
•It is typically used for finding the shortest path in an unweighted
graph or exploring all reachable nodes from a starting point.
Example Walkthrough
Real-World Applications
1. Unweighted Shortest Path: Finding the minimum number of steps to reach a destination.
2. Web Crawling: Exploring linked pages starting from one URL.
3. Network Broadcasting: Spreading a message in a network.
Depth-First Search (DFS)
• Algorithm:
• Start from a source node.
• Explore as far as possible along each branch before backtracking.
• Use a stack (implicit in recursive calls or explicit).
• Steps:
• Push the starting node onto the stack.
• Pop a node, mark it as visited, and push all its unvisited neighbors.
• Repeat until the stack is empty.
Depth-First Search (DFS)
•Time Complexity: O(V+E).
•Space Complexity: O(V) for recursion or stack.
•Example Graph:
•Nodes: A, B, C, D, E
•DFS from A: Visit order: A → B → D → E → C → F
Concept Overview
• DFS explores as far as possible along each branch
before backtracking.
• It’s useful for problems that involve exhaustive
exploration, such as detecting cycles or solving
puzzles.
Example Walkthrough
• Steps for DFS starting at 'A’:
• Initialize:Stack: ['A’]
• Visited: {}
• DFS Order: []
• Process:
• Pop 'A': Visit → Push neighbors ('C', 'B') onto stack.
• Stack: ['C', 'B’]
• Visited: {'A’}
• DFS Order: ['A’]
• Process 'B’:
• Pop 'B': Visit → Push neighbors ('E', 'D') onto stack.
• Stack: ['C', 'E', 'D’]
• Visited: {'A', 'B’}
• DFS Order: ['A', 'B’]
• Process 'D’:
• Pop 'D': Visit (no neighbors to push).
• Stack: ['C', 'E']Visited: {'A', 'B', 'D’}
• DFS Order: ['A', 'B', 'D’]
• Continue until stack is empty.
• DFS Order: ['A', 'B', 'D', 'E', 'C', 'F']
Depth-First Search (DFS)
Real-World Applications
1. Cycle Detection: Check if a graph contains cycles.
2. Topological Sorting: Order tasks with dependencies (e.g., prerequisites).
3. Maze Solving: Explore all possible paths exhaustively.
Comparison (Summary)
• BFS is level-by-level, good for shortest paths.
• DFS is exhaustive, suitable for problems requiring complete exploration.
Comparison of BFS and DFS
Use Cases:
• BFS is optimal for problems like finding the
shortest path in an unweighted graph because
it explores level by level.
• DFS is better for applications like finding
connected components, topological sorting, or
detecting cycles.
Memory Usage:
• BFS requires more memory when the graph is
wide (many neighbors for each node) because
all neighbors are added to the queue.
• DFS can consume more memory in deep graphs
(with long paths) due to recursion stack or
explicit stack usage.
Comparison of BFS and DFS
Applications of BFS
1. Finding the Shortest Path:
1. BFS ensures that the shortest path (in terms of the number of edges) in an unweighted graph is found
first.
2. Example: Navigating from one city to another on a subway map where all edges represent equal costs.
2. Web Crawling:
1. BFS systematically explores web pages level by level, starting with links on a homepage and moving
deeper into the structure of a website.
3. Network Broadcasting:
1. BFS simulates broadcasting in computer networks, ensuring that information reaches all nodes in the
minimum number of hops.
Comparison of BFS and DFS
Applications of DFS
1. Cycle Detection:
1. DFS can determine if a graph contains cycles by backtracking to previously visited nodes.
2. Example: Verifying a directed graph for feedback loops.
2. Topological Sorting:
1. DFS is used to order tasks or events that have dependencies, such as job scheduling or course
prerequisites.
2. Example: Determining the sequence of subjects a student must take to complete their degree.
3. Maze Solving:
1. DFS explores paths deeply, making it suitable for solving mazes or puzzles where backtracking is required.
Comparison of BFS and DFS
Key Observations:
Key Observations:
Traversal Pattern:
• BFS covers nodes in layers, expanding outward from the starting point.
• DFS dives deep into one branch before backtracking to explore others.
• BFS is ideal for problems like shortest pathfinding (e.g., routing networks).
• DFS is better for exploring connected components or solving puzzles (e.g., maze navigation).
Visualization: