## Algorithm

Depth-First Search (DFS) Algorithm:

1. Start at the initial node: Begin at the initial (or source) node in the graph.

2. Mark the node as visited: Mark the current node as visited to avoid revisiting it.

3. Explore neighbors: Visit an unvisited neighbor of the current node. If there are multiple neighbors, choose one arbitrarily.

4. Recursion: Recursively apply steps 2-3 to the chosen neighbor. This process continues until there are no more unvisited neighbors.

5. Backtrack: If there are no unvisited neighbors, backtrack to the previous node and repeat step 3 for any unvisited neighbors of that node.

6. Repeat: Repeat steps 2-5 until all nodes in the graph are visited.

The key characteristic of DFS is that it explores as far as possible along each branch before backtracking. It can be implemented using recursion or a stack data structure.

## Code Examples

### #1 DFS Implementation in Python

```Code - Python Programming```

``````class Graph:
def __init__(self):
self.graph = {}

def add_edge(self, u, v):
if u not in self.graph:
self.graph[u] = []
self.graph[u].append(v)

def dfs(self, start, visited=None):
if visited is None:
visited = set()

print(start, end=' ')

for neighbor in self.graph.get(start, []):
if neighbor not in visited:
self.dfs(neighbor, visited)

# Example usage:
# Create a graph
g = Graph()

# Add edges to the graph

# Perform DFS starting from node 1
print("DFS starting from node 1:")
g.dfs(1)
``````
Copy The Code &

### #2 DFS Implementation in Java

```Code - Java Programming```

``````import java.util.*;

class Graph {
private int vertices;

public Graph(int vertices) {
this.vertices = vertices;

for (int i = 0; i  <  vertices; i++) {
}
}

public void addEdge(int vertex, int neighbor) {
}

public void dfs(int startVertex) {
boolean[] visited = new boolean[vertices];
dfsRecursive(startVertex, visited);
}

private void dfsRecursive(int vertex, boolean[] visited) {
visited[vertex] = true;
System.out.print(vertex + " ");

for (int neighbor : adjacencyList[vertex]) {
if (!visited[neighbor]) {
dfsRecursive(neighbor, visited);
}
}
}
}

public class DFSExample {
public static void main(String[] args) {
Graph graph = new Graph(6);

System.out.println("Depth-First Traversal starting from vertex 0:");
graph.dfs(0);
}
}
``````
Copy The Code &

### #3 DFS Implementation in C

```Code - C Programming```

``````#include <stdio.h>
#include <stdlib.h>

// Structure to represent a node in the adjacency list
struct Node {
int data;
struct Node* next;
};

// Structure to represent the graph
struct Graph {
int vertices;
int* visited;
};

// Function to create a new node
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}

// Function to create a graph with 'vertices' number of vertices
struct Graph* createGraph(int vertices) {
struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
graph->vertices = vertices;
graph->adjacencyList = (struct Node**)malloc(vertices * sizeof(struct Node*));
graph->visited = (int*)malloc(vertices * sizeof(int));

for (int i = 0; i  <  vertices; i++) {
graph->visited[i] = 0; // Initialize all vertices as not visited
}

return graph;
}

// Function to add an edge to the graph
void addEdge(struct Graph* graph, int src, int dest) {
// Add an edge from src to dest
struct Node* newNode = createNode(dest);

// For undirected graphs, add an edge from dest to src as well
newNode = createNode(src);
}

// Depth-First Search function
void DFS(struct Graph* graph, int vertex) {
// Mark the current vertex as visited
graph->visited[vertex] = 1;
printf("%d ", vertex);

// Traverse all adjacent vertices
struct Node* temp = graph->adjacencyList[vertex];
while (temp != NULL) {
int adjVertex = temp->data;
}
temp = temp->next;
}
}

int main() {
// Create a graph with 5 vertices
struct Graph* graph = createGraph(5);

// Add edges to the graph

printf("Depth-First Traversal starting from vertex 0: ");
DFS(graph, 0);

return 0;
}
``````
Copy The Code &

### #4 DFS Implementation in C++

```Code - C++ Programming```

``````#include <iostream>
#include <vector>
#include <stack>

using namespace std;

class Graph {
int V; // number of vertices
vector < vector<int>> adjList; // adjacency list

public:
Graph(int vertices) : V(vertices), adjList(vertices) {}

void addEdge(int v, int w) {
}

void DFS(int startVertex) {
// Create a boolean array to keep track of visited vertices
vector < bool> visited(V, false);

// Create a stack for DFS
stack<int> stack;

// Push the current vertex to the stack and mark it as visited
stack.push(startVertex);
visited[startVertex] = true;

while (!stack.empty()) {
// Get the top vertex from the stack
int currentVertex = stack.top();
cout << currentVertex << " ";
stack.pop();

// Traverse all adjacent vertices of the popped vertex
// If the adjacent vertex is not visited, push it to the stack and mark it as visited
}
}
}
}
};

int main() {
Graph g(5); // Create a graph with 5 vertices

cout << "DFS starting from vertex 0: ";
g.DFS(0);

return 0;
}
``````
Copy The Code &