0% found this document useful (0 votes)
12 views2 pages

DFS

The document describes depth-first search (DFS) traversal on a graph data structure implemented in Java. It defines a Graph class with methods to add edges between vertices and perform DFS traversal by recursively exploring each vertex and its neighbors.

Uploaded by

hello world
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views2 pages

DFS

The document describes depth-first search (DFS) traversal on a graph data structure implemented in Java. It defines a Graph class with methods to add edges between vertices and perform DFS traversal by recursively exploring each vertex and its neighbors.

Uploaded by

hello world
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

DFS

-----------------------------------------------------------------------------------
import java.io.*;
import java.util.*;

class Graph {
private int V; // No. of vertices

private LinkedList<Integer> adj[];

@SuppressWarnings("unchecked") Graph(int v)
{
V = v;
adj = new LinkedList[v];
for (int i = 0; i < v; ++i)
adj[i] = new LinkedList();
}

void addEdge(int v, int w)


{
adj[v].add(w); // Add w to v's list.
}

void DFSUtil(int v, boolean visited[])


{

visited[v] = true;
System.out.print(v + " ");

Iterator<Integer> i = adj[v].listIterator();
while (i.hasNext()) {
int n = i.next();
if (!visited[n])
DFSUtil(n, visited);
}
}

void DFS(int v)
{

boolean visited[] = new boolean[V];

DFSUtil(v, visited);
}

public static void main(String args[])


{
Graph g = new Graph(4);

g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);

System.out.println(
"Following is Depth First Traversal "
+ "(starting from vertex 2)");

g.DFS(2);
}
}

You might also like