DFS Algorithm

The Depth-First Search (DFS) Algorithm is a popular graph traversal technique used in computer science and mathematics for exploring and traversing tree or graph data structures. It starts at the root node or any arbitrary node and explores as far as possible along each branch before backtracking. The primary goal of the DFS algorithm is to visit all the nodes in a graph or tree, marking each visited node and keeping track of the traversed path. This algorithm is particularly useful in various applications such as network analysis, pathfinding, topological sorting, and solving puzzles like mazes. The DFS algorithm can be implemented using recursion or an explicit stack data structure. In the recursive approach, the algorithm calls itself for each unvisited adjacent node until it reaches a dead-end, at which point it backtracks to the previous node and continues the exploration. In the stack-based approach, the algorithm iteratively pushes the current node onto the stack, marks it as visited, and proceeds to the next unvisited adjacent node. When a dead-end is reached, the algorithm pops the top node off the stack and backtracks to explore other branches. The DFS algorithm has a time complexity of O(V + E), where V is the number of vertices and E is the number of edges in the graph, making it an efficient approach to traverse large graphs or trees.
#include <iostream>
using namespace std;
int v = 4;
void DFSUtil_(int graph[4][4], bool visited[], int s)
{
	visited[s] = true;
	cout << s << " ";
	for (int i = 0; i < v; i++)
	{
		if (graph[s][i] == 1 && visited[i] == false)
		{
			DFSUtil_(graph, visited, i);
		}
	}
}

void DFS_(int graph[4][4], int s)
{
	bool visited[v];
	memset(visited, 0, sizeof(visited));
	DFSUtil_(graph, visited, s);
}

int main()
{
	int graph[4][4] = {{0, 1, 1, 0}, {0, 0, 1, 0}, {1, 0, 0, 1}, {0, 0, 0, 1}};
	cout << "DFS: ";
	DFS_(graph, 2);
	cout << endl;
	return 0;
}

LANGUAGE:

DARK MODE: