A comprehensive implementation and comparative study of the two fundamental graph traversal algorithms: Breadth-First Search and Depth-First Search, implemented using C and Adjacency Matrices.
Graph traversal is the process of visiting every vertex in a graph exactly once. This repository breaks down the two most common methods for traversing non-linear data structures.
- Strategy: Explore the neighbor nodes first, before moving to the next level neighbors.
- Analogy: Like ripples in a pond spreading outward.
- Core Logic: Uses a Queue (FIFO) data structure.
- Best For: Finding the shortest path in unweighted graphs.
- Strategy: Explore as far as possible along each branch before backtracking.
- Analogy: Like exploring a maze by following one path until you hit a wall.
- Core Logic: Uses a Stack (LIFO) (Recursion).
- Best For: Cycle detection and pathfinding.
| Feature | Breadth-First Search (BFS) | Depth-First Search (DFS) |
|---|---|---|
| Data Structure | Queue (Manual Array) | Stack (Recursive Call Stack) |
| Approach | Level-order (Wide) | Depth-order (Deep) |
| Time Complexity |
|
|
| Space Complexity | ||
| Shortest Path | Guaranteed for unweighted | Not guaranteed |
- Initialize a queue and a visited array.
- Enqueue the starting node and mark as visited.
- While the queue is not empty:
- Dequeue a node and process it.
- Enqueue all its unvisited neighbors and mark them visited.
- Start at the root node.
- Mark node as visited and process it.
- For every unvisited neighbor, recursively call the DFS function.
- Backtrack when no more unvisited neighbors exist.
You need a C compiler (like GCC) installed on your system.
-
Clone the repository:
git clone [https://github.com/Aaron-Garvin/Graph-Traversal-Algorithms-DFS-and-BFS.git](https://github.com/Aaron-Garvin/Graph-Traversal-Algorithms-DFS-and-BFS.git) cd Graph-Traversal-Algorithms-DFS-and-BFS -
Run BFS:
gcc "01. Breadth_First_Search/main.c" -o bfs ./bfs -
Run DFS:
gcc "02. Depth_First_Search/main.c" -o dfs ./dfs
├── 01. Breadth_First_Search/ # Level-order implementation
│ ├── main.c # BFS Source Code
│ └── README.md # BFS detailed documentation
├── 02. Depth_First_Search/ # Deep-dive implementation
│ ├── main.c # DFS Source Code
│ └── README.md # DFS detailed documentation
├── .gitignore # Prevents binary/temp files
├── LICENSE # MIT License
└── README.md # Main Documentation (This file)
Contributions, issues, and feature requests are welcome! Feel free to check the issues page if you want to contribute.
Distributed under the MIT License. See LICENSE for more information.