
DFS (Depth First Search) is an algorithm used to traverse a graph (or tree) by starting at a given vertex and moving as far as possible along one path before backtracking to explore other paths. It is widely used for tasks such as full graph traversal, path existence checks, and connected component detection.
visited array or set).Below is a simple example using an adjacency list and a recursive DFS approach in Java.
import java.util.ArrayList;
import java.util.List;
public class DFSExample {
private List<List<Integer>> graph; // Adjacency list
private boolean[] visited;
public DFSExample(int n) {
graph = new ArrayList<>();
for (int i = 0; i < n; i++) {
graph.add(new ArrayList<>());
}
visited = new boolean[n];
}
// Add an undirected edge
public void addEdge(int u, int v) {
graph.get(u).add(v);
graph.get(v).add(u);
}
public void dfs(int current) {
visited[current] = true;
System.out.print(current + " ");
for (int next : graph.get(current)) {
if (!visited[next]) {
dfs(next);
}
}
}
// Reset the visited array for another DFS run
public void resetVisited() {
for (int i = 0; i < visited.length; i++) {
visited[i] = false;
}
}
}
public class DFSTest {
public static void main(String[] args) {
// Create a graph with 6 vertices (0 ~ 5)
DFSExample dfsGraph = new DFSExample(6);
// Add undirected edges
dfsGraph.addEdge(0, 1);
dfsGraph.addEdge(0, 2);
dfsGraph.addEdge(1, 3);
dfsGraph.addEdge(2, 4);
dfsGraph.addEdge(2, 5);
System.out.println("DFS start (from vertex 0):");
dfsGraph.dfs(0);
// Possible output (depending on adjacency order): 0 1 3 2 4 5
// Reset visited array to reuse
dfsGraph.resetVisited();
System.out.println("\nDFS start (from vertex 3):");
dfsGraph.dfs(3);
}
}
Running the above code will perform DFS starting from vertex 0 (and then from 3 after resetting), printing the visited vertices in DFS order.
Below is a similar example in Python, using a dictionary for the adjacency list and a recursive DFS function.
class DFSExample:
def __init__(self, n):
# Assume vertices 0..n-1
self.graph = {i: [] for i in range(n)}
self.visited = [False] * n
def add_edge(self, u, v):
# Undirected edge: add both ways
self.graph[u].append(v)
self.graph[v].append(u)
def dfs(self, current):
self.visited[current] = True
print(current, end=' ')
for nxt in self.graph[current]:
if not self.visited[nxt]:
self.dfs(nxt)
def reset_visited(self):
self.visited = [False] * len(self.visited)
def test_dfs():
dfs_graph = DFSExample(6)
# Add edges
dfs_graph.add_edge(0, 1)
dfs_graph.add_edge(0, 2)
dfs_graph.add_edge(1, 3)
dfs_graph.add_edge(2, 4)
dfs_graph.add_edge(2, 5)
print("DFS start (from vertex 0):")
dfs_graph.dfs(0)
# Example output: 0 1 3 2 4 5
dfs_graph.reset_visited()
print("\nDFS start (from vertex 3):")
dfs_graph.dfs(3)
if __name__ == "__main__":
test_dfs()
| Aspect | DFS (Depth First Search) | BFS (Breadth First Search) |
|---|---|---|
| Data Structure | Stack or Recursion | Queue |
| Visit Order | Go deep along a path, then backtrack | Layer-by-layer from the start vertex |
| Typical Uses | Path exploration, backtracking, topological sort, connected components | Shortest path in unweighted graphs, level-order traversal |
When analyzing a stock, one of the first financial indicators you’ll encounter is EPS, or Earnings Per Share. It’s one… Read More
When you look at a stock’s profile on a financial website, one of the first things you’ll see is its… Read More
In the world of open-source software, simplicity and flexibility are often just as important as legal protection. That’s why the… Read More
If you want your software to be open source, but still compatible with commercial use—and not as restrictive as the… Read More
When it comes to open-source software, developers and businesses alike need licenses that balance freedom, legal clarity, and long-term security.… Read More
If you’re working on open-source projects or choosing third-party libraries for your software, understanding software licenses is essential. Among the… Read More