From 077c1e746a7e36de557678f5f83002075e075097 Mon Sep 17 00:00:00 2001 From: Nkeiruka <58699506+Kxiru@users.noreply.github.com> Date: Thu, 14 Nov 2024 16:58:48 +0000 Subject: [PATCH] Added Depth First Search concept and example. --- Depth First Search/DepthFirstSearch.java | 55 ++++++++++++ Depth First Search/DepthFirstSearch.md | 104 +++++++++++++++++++++++ 2 files changed, 159 insertions(+) create mode 100644 Depth First Search/DepthFirstSearch.java create mode 100644 Depth First Search/DepthFirstSearch.md diff --git a/Depth First Search/DepthFirstSearch.java b/Depth First Search/DepthFirstSearch.java new file mode 100644 index 0000000..a506718 --- /dev/null +++ b/Depth First Search/DepthFirstSearch.java @@ -0,0 +1,55 @@ +import java.util.*; + +public class DepthFirstSearch { + + // Adjacency list for the graph + private List> adjList; + + // Constructor to initialize the adjacency list + public DepthFirstSearch(int numVertices) { + adjList = new ArrayList<>(); + for (int i = 0; i < numVertices; i++) { + adjList.add(new ArrayList<>()); + } + } + + // Method to add an edge to the graph + public void addEdge(int v, int w) { + adjList.get(v).add(w); + adjList.get(w).add(v); // For directed graphs, remove this line + } + + // DFS traversal from a given starting node + public void dfs(int start) { + boolean[] visited = new boolean[adjList.size()]; + dfsUtil(start, visited); + } + + // Utility method for recursive DFS + private void dfsUtil(int vertex, boolean[] visited) { + visited[vertex] = true; + System.out.print(vertex + " "); + + for (int adj : adjList.get(vertex)) { + if (!visited[adj]) { + dfsUtil(adj, visited); + } + } + } + + // Main method to demonstrate DFS + public static void main(String[] args) { + DepthFirstSearch graph = new DepthFirstSearch(6); + + // Adding edges to the graph + graph.addEdge(0, 1); + graph.addEdge(0, 2); + graph.addEdge(1, 3); + graph.addEdge(1, 4); + graph.addEdge(2, 5); + + // Perform DFS starting from vertex 0 + System.out.println("Depth First Search starting from vertex 0:"); + graph.dfs(0); + } +} diff --git a/Depth First Search/DepthFirstSearch.md b/Depth First Search/DepthFirstSearch.md new file mode 100644 index 0000000..105583f --- /dev/null +++ b/Depth First Search/DepthFirstSearch.md @@ -0,0 +1,104 @@ +# Overview of the Depth First Search (DFS) Code in Java πŸ’» + +## What's Happening in the Code? ❓ +The provided Java code implements Depth First Search (DFS), a fundamental graph traversal algorithm. Let me walk you through the details! + +### 1. **Setting Up the Graph** πŸ“ +We start by creating a graph structure using an **adjacency list**, represented by a `List` of `List`. Each index in the main list corresponds to a vertex, and each sublist contains its neighboring vertices. This makes it easy to keep track of which nodes are connected. + +```java +private List> adjList; +``` + +### 2. **Constructing the Graph** βš™οΈ +The `DepthFirstSearch` constructor initializes the adjacency list with `numVertices` empty lists: + +```java +public DepthFirstSearch(int numVertices) { + adjList = new ArrayList<>(); + for (int i = 0; i < numVertices; i++) { + adjList.add(new ArrayList<>()); + } +} +``` + +### 3. **Adding Edges** βž• +The `addEdge` method links two vertices, `v` and `w`, by adding each to the other's adjacency list: + +```java +public void addEdge(int v, int w) { + adjList.get(v).add(w); + adjList.get(w).add(v); // Remove this for directed graphs +} +``` + +This makes it an **undirected graph**, where the connection between nodes goes both ways. + +### 4. **The DFS Method** πŸ”„ +The main `dfs` method sets up an array called `visited` to keep track of which nodes have been visited during the traversal: + +```java +public void dfs(int start) { + boolean[] visited = new boolean[adjList.size()]; + dfsUtil(start, visited); +} +``` + +### 5. **DFS Utility Method** ❀️ +The `dfsUtil` method is the heart of the algorithm. It recursively visits nodes and prints them as it goes: + +```java +private void dfsUtil(int vertex, boolean[] visited) { + visited[vertex] = true; + System.out.print(vertex + " "); + + for (int adj : adjList.get(vertex)) { + if (!visited[adj]) { + dfsUtil(adj, visited); + } + } +} +``` +- **Visit**: The current node is marked as visited and printed. +- **Recur**: For each unvisited neighbor, `dfsUtil` is called recursively. + +### 6. **Main Method** πŸ’ͺ +Finally, the `main` method demonstrates the DFS by building a sample graph and starting the traversal from vertex `0`: + +```java +public static void main(String[] args) { + DepthFirstSearch graph = new DepthFirstSearch(6); + + // Adding edges to the graph + graph.addEdge(0, 1); + graph.addEdge(0, 2); + graph.addEdge(1, 3); + graph.addEdge(1, 4); + graph.addEdge(2, 5); + + // Perform DFS starting from vertex 0 + System.out.println("Depth First Search starting from vertex 0:"); + graph.dfs(0); +} +``` + +## What Happens When You Run It? ⏳ +1. The graph is created with 6 vertices. +2. Edges are added between the vertices to form connections. +3. DFS starts from vertex `0` and traverses through its neighbors, exploring as far as possible along each branch before backtracking. + +### Example Output: βœ… +If you run the code, you might see an output like: +``` +Depth First Search starting from vertex 0: +0 1 3 4 2 5 +``` +This output shows the order in which the vertices are visited during the DFS traversal. + +## Fun Fact: 🧐 +DFS is great for exploring maze-like structures and finding connected components in a graph. It dives deep into each path before backtracking, making it perfect for tasks like solving puzzles or exploring tree data structures. + +And that’s how DFS works in Java! + +### Created by +Nkeiruka Whenu \ No newline at end of file