How do I perform depth-first search (DFS) recursively in TypeScript?
Depth-first search (DFS) can be implemented recursively in TypeScript by exploring each node and its neighbors before backtracking.
Depth-first search (DFS) is a classic algorithm for traversing or searching tree or graph data structures. The idea behind DFS is to explore as far as possible along each branch before backtracking. In TypeScript, DFS can be implemented recursively by starting from a given node, marking it as visited, and then recursively visiting each of its unvisited neighbors. This algorithm is particularly useful for solving problems such as detecting cycles in graphs, topological sorting, and pathfinding in mazes. DFS can be applied to both directed and undirected graphs, and its time complexity is O(V + E), where V is the number of vertices and E is the number of edges. Understanding DFS is fundamental for working with graph algorithms and is frequently encountered in technical interviews and real-world applications.