Skip to content

Commit b6c43bd

Browse files
author
jsroyal
committed
Depth First Traversal
1 parent 5d0422e commit b6c43bd

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

README.md

+2
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,8 @@ This is a collection of algorithms and data structures which I've implement over
128128
* A* path finding algorithm
129129
* Maximum flow
130130
- Push-Relabel
131+
* Graph Traversal
132+
- Depth First Traversal
131133

132134
## Search
133135
* Get index of value in array
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import java.util.Stack;
2+
3+
//implemented Depth First Travesal in given "Directed graph" (Adjacany matrix)
4+
class DepthFirstTraversal {
5+
6+
public static int[] arr;
7+
public static int k = 0;
8+
9+
public static void depthFirstTraversal(int[][] a, int[] visited,int source){
10+
for (int i = 0; i < visited.length; i++) {
11+
visited[i] = -1;
12+
}
13+
Stack<Integer>stack = new Stack();
14+
int element = source;
15+
int i = source;
16+
int n = visited.length - 1;
17+
arr[k] = element;
18+
k++;
19+
visited[source] = 1;
20+
stack.push(source);
21+
22+
while (!stack.isEmpty()) {
23+
element = stack.peek();
24+
i = element;
25+
while (i <= n) {
26+
if (a[element][i] == 1 && visited[i] == -1) {
27+
stack.push(i);
28+
visited[i] = 1;
29+
element = i;
30+
i = 1;
31+
arr[k] = element;
32+
k++;
33+
continue;
34+
}
35+
i++;
36+
}
37+
stack.pop();
38+
}
39+
}
40+
41+
42+
public static void main(String[] args) {
43+
int n = 5; //no. of vertic
44+
int[] visited = new int[n];
45+
arr = new int[n];
46+
// Adjacency Matrix of graph
47+
int[][] a = new int[][] {{0, 1, 0, 1, 0},
48+
{0, 0, 0, 1, 1},
49+
{1, 1, 0, 1, 0},
50+
{0, 0, 0, 0, 0},
51+
{0, 0, 1, 0, 0}};
52+
depthFirstTraversal(a, visited, 0);
53+
for (int element : arr) {
54+
if(element != -1) //not direct connected
55+
System.out.println(element);
56+
}
57+
}
58+
}
59+

0 commit comments

Comments
 (0)