Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 0a8c483

Browse filesBrowse files
authored
Merge pull request dubesar#49 from chrisom79/patch-1
Create DFS according to Graph
2 parents f7f0008 + 562f7df commit 0a8c483
Copy full SHA for 0a8c483

File tree

Expand file treeCollapse file tree

1 file changed

+52
-0
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+52
-0
lines changed

‎Algorithms/DepthFirstSearch.java

Copy file name to clipboard
+52Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package Algorithms;
2+
3+
import java.util.Iterator;
4+
import java.util.LinkedList;
5+
6+
public class DepthFirstSearch {
7+
public static void main(String args[])
8+
{
9+
Graph g = new Graph(4);
10+
11+
g.addEdge(0, 1);
12+
g.addEdge(0, 2);
13+
g.addEdge(1, 2);
14+
g.addEdge(2, 0);
15+
g.addEdge(2, 3);
16+
g.addEdge(3, 3);
17+
18+
g.DFS(2);
19+
}
20+
}
21+
22+
23+
class Graph {
24+
private int numVertices;
25+
private LinkedList<Integer> adj[];
26+
private boolean visited[];
27+
28+
public Graph(int vertices) {
29+
numVertices = vertices;
30+
adj = new LinkedList[vertices];
31+
visited = new boolean[vertices];
32+
33+
for (int i = 0; i < vertices; i++)
34+
adj[i] = new LinkedList<Integer>();
35+
}
36+
37+
void addEdge(int src, int dest) {
38+
adj[src].add(dest);
39+
}
40+
41+
void DFS(int vertex) {
42+
visited[vertex] = true;
43+
System.out.print(vertex + " ");
44+
45+
Iterator ite = adj[vertex].listIterator();
46+
while (ite.hasNext()) {
47+
int adj = (int) ite.next();
48+
if (!visited[adj])
49+
DFS(adj);
50+
}
51+
}
52+
}

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.