forked from PrajaktaSathe/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
this is a dfs algorithm, specially meant for beginners. PrajaktaSathe#2
- Loading branch information
1 parent
1ff670b
commit c18dee8
Showing
1 changed file
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
import java.util.LinkedList; | ||
|
||
public class GraphDFS { | ||
private LinkedList<Integer>[] adjLists; | ||
private boolean[] visited; | ||
|
||
// Graph Constructor | ||
GraphDFS(int vertices) { | ||
adjLists = new LinkedList[vertices]; | ||
visited = new boolean[vertices]; | ||
|
||
for (int i = 0; i < vertices; i++) { | ||
adjLists[i] = new LinkedList<>(); | ||
} | ||
} | ||
|
||
// Add an edge to the graph | ||
void addEdge(int src, int dest) { | ||
adjLists[src].add(dest); | ||
} | ||
|
||
// DFS traversal of the vertices reachable from v | ||
void DFS(int vertex) { | ||
visited[vertex] = true; | ||
System.out.print(vertex + " "); | ||
|
||
for (int adj : adjLists[vertex]) { | ||
if (!visited[adj]) { | ||
DFS(adj); | ||
} | ||
} | ||
} | ||
|
||
public static void main(String[] args) { | ||
GraphDFS graph = new GraphDFS(4); | ||
|
||
graph.addEdge(0, 1); | ||
graph.addEdge(0, 2); | ||
graph.addEdge(1, 2); | ||
graph.addEdge(2, 0); | ||
graph.addEdge(2, 3); | ||
graph.addEdge(3, 3); | ||
|
||
System.out.println("Depth First Search starting from vertex 2:"); | ||
graph.DFS(2); | ||
} | ||
} |