-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDFS.java
More file actions
63 lines (52 loc) · 1.66 KB
/
DFS.java
File metadata and controls
63 lines (52 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package com.anudev.ds.graphs;
import java.util.Stack;
/**
* DFS works in manner similar to preorder traversal of trees. Internally
* algorithm uses stacks. Need to take care of 2 things: 1) visiting a
* vertex 2) Exploration of vertex
* <p>
* Depth First Search (DFS) algorithm traverses a graph in a depth ward
* motion and uses a stack to remember to get the next vertex to start
* a search, when a dead end occurs in any iteration.
*/
public class DFS {
private final Vertex[] vertices;
private final int[][] adjMatrix;
private final Stack<Integer> stack;
private int vertexCount;
public DFS(int numberOfVertices) {
stack = new Stack<>();
adjMatrix = new int[numberOfVertices][numberOfVertices];
vertices = new Vertex[numberOfVertices];
}
public void addVertex(char lab) {
vertices[vertexCount] = new Vertex(lab);
vertexCount++;
}
public void addEdge(int start, int end) {
adjMatrix[start][end] = 1;
adjMatrix[end][start] = 1;
}
public void performDFS(int value) {
stack.push(value);
vertices[value].setVisited(true);
// keep pushing
while (!stack.isEmpty()) {
int v = getAdjUnvisitedMatrix(stack.peek());
if (v != -1) {
vertices[v].setVisited(true);
stack.push(v);
} else {
stack.pop();
}
}
}
private int getAdjUnvisitedMatrix(int x) {
for (int i = 0; i < vertexCount; i++) {
if (adjMatrix[x][i] == 1 && !vertices[i].isVisited()) {
return i;
}
}
return -1;
}
}