CSC211 ยท 2081 ยท 5 marks
Write short notes on: a. Breadth First traversal of graph b. TOH
Write short notes on: a. Breadth First traversal of graph b. TOH [5]
Short Notes
a. Breadth First Search (BFS) Traversal of Graph
Definition: BFS is one of the simplest methods of graph searching/traversal. It explores a graph level by level, visiting all neighbors of a vertex before moving to the next level.
Algorithm / Steps:
- Choose some vertex arbitrarily as the root (starting vertex).
- Visit the root and add all vertices and edges that are incident on the root. These newly added vertices form Level 1 of the BFS tree.
- From the set of vertices at Level 1, find other vertices that are connected by edges to Level 1 vertices. These form Level 2.
- Repeat the above step until all vertices are visited/added.
- A queue data structure is used to keep track of vertices to be visited next.
Example:
Graph:
A
/ \
B C
/ \
D E
BFS Order: A -> B -> C -> D -> E
Key Features:
- Uses a Queue (FIFO)
- Visits vertices in order of their distance from the source
- Guarantees the shortest path in an unweighted graph
b. Tower of Hanoi (TOH)
Definition:
Tower of Hanoi is a classic recursive problem that involves moving n disks from a source peg to a destination peg using an auxiliary (helper) peg, following specific rules.
Rules:
- Only one disk can be moved at a time.
- A disk can only be placed on top of a larger disk or on an empty peg.
- Only the top disk of any peg can be moved.
Recursive Algorithm:
To move n disks from Source (S) to Destination (D) using Auxiliary (A):
- Move
n-1disks from S to A (using D as auxiliary) - Move the nth (largest) disk from S to D
- Move
n-1disks from A to D (using S as auxiliary)
Example (n = 3 disks, S -> D using A):
| Step | Move |
|---|---|
| 1 | S -> D |
| 2 | S -> A |
| 3 | D -> A |
| 4 | S -> D |
| 5 | A -> S |
| 6 | A -> D |
| 7 | S -> D |
Total moves = 2^n - 1 = 2^3 - 1 = 7 moves
Key Features:
- Classic example of recursion
- Minimum number of moves required = 2^n - 1
- Time Complexity: O(2^n)
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.