Skip to content

Commit 8dec66f

Browse files
committed
Added Graph DFS
1 parent 0ad09af commit 8dec66f

File tree

2 files changed

+81
-0
lines changed

2 files changed

+81
-0
lines changed

src/graphs/Graph.java

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
package graphs;
2+
//credits to geekforgeeks.com.
3+
import java.util.*;
4+
5+
class Graph
6+
{
7+
private int V; // No. of vertices
8+
9+
// Array of lists for Adjacency List Representation
10+
private LinkedList<Integer> adj[];
11+
12+
// Constructor
13+
@SuppressWarnings({ "unchecked", "rawtypes" })
14+
Graph(int v)
15+
{
16+
V = v;
17+
adj = new LinkedList[v];
18+
for (int i=0; i<v; ++i)
19+
adj[i] = new LinkedList();
20+
}
21+
22+
//Function to add an edge into the graph
23+
void addEdge(int v, int w)
24+
{
25+
adj[v].add(w); // Add w to v's list.
26+
}
27+
28+
// A function used by DFS
29+
void DFSUtil(int v,boolean visited[])
30+
{
31+
// Mark the current node as visited and print it
32+
visited[v] = true;
33+
System.out.print(v+" ");
34+
35+
// Recur for all the vertices adjacent to this vertex
36+
Iterator<Integer> i = adj[v].listIterator();
37+
38+
while (i.hasNext())
39+
{
40+
int n = i.next();
41+
if (!visited[n])
42+
DFSUtil(n, visited);
43+
}
44+
}
45+
46+
// The function to do DFS traversal. It uses recursive DFSUtil()
47+
void DFS(int v)
48+
{
49+
// Mark all the vertices as not visited(set as
50+
// false by default in java)
51+
boolean visited[] = new boolean[V];
52+
53+
// Call the recursive helper function to print DFS traversal
54+
DFSUtil(v, visited);
55+
}
56+
57+
public static void main(String args[])
58+
{
59+
Graph g = new Graph(4);
60+
61+
g.addEdge(0, 1);
62+
g.addEdge(0, 2);
63+
g.addEdge(1, 2);
64+
g.addEdge(2, 0);
65+
g.addEdge(2, 3);
66+
g.addEdge(3, 3);
67+
68+
System.out.println("Following is Depth First Traversal "+
69+
"(starting from vertex 2)");
70+
71+
g.DFS(2);
72+
}
73+
}

src/graphs/package-info.java

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
/**
2+
*
3+
*/
4+
/**
5+
* @author whamsy
6+
*
7+
*/
8+
package graphs;

0 commit comments

Comments
 (0)