forked from techpanja/interviewproblems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDirectedGraph.java
More file actions
80 lines (70 loc) · 2.07 KB
/
DirectedGraph.java
File metadata and controls
80 lines (70 loc) · 2.07 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package graphs.graph;
import java.util.List;
/**
* Directed AbstractGraph.
* User: rpanjrath
* Date: 10/24/13
* Time: 5:58 PM
*/
public class DirectedGraph extends AbstractGraph {
private Vertex[] vertexes;
private int maxSize;
private int currentSize;
public DirectedGraph(int maxSize) {
this.currentSize = 0;
this.maxSize = maxSize;
this.vertexes = new Vertex[maxSize];
}
@Override
public int getCurrentSize() {
return this.currentSize;
}
@Override
public Vertex[] getVertexesAsArray() {
return this.vertexes;
}
@Override
public int getMaxSize() {
return this.maxSize;
}
@Override
public void setCurrentSize(int currentSize) {
this.currentSize = currentSize;
}
@Override
public boolean addEdge(String fromVertex, String toVertex) {
Vertex fromV = new Vertex(fromVertex);
Vertex toV = new Vertex(toVertex);
if (!isVertexExisting(fromV))
addVertex(fromV);
else {
fromV = getVertex(fromVertex);
}
if (!isVertexExisting(toV))
addVertex(toV);
else {
toV = getVertex(toVertex);
}
return addEdge(fromV, toV);
}
@Override
public boolean addEdge(Vertex fromVertex, Vertex toVertex) {
if (!isVertexExisting(fromVertex) || !isVertexExisting(toVertex)) {
return false;
}
if (fromVertex.toString().equalsIgnoreCase(toVertex.toString())) {
System.out.println("Start and end vertex \"" + fromVertex + "\" should be different.");
System.out.println();
return false;
}
if (!canAddVertex(toVertex, fromVertex.getDependsOn())) {
System.out.println("Vertex \"" + fromVertex + "\" already depends on \"" + toVertex + "\"");
System.out.println();
return false;
}
List<Vertex> dependsOn = fromVertex.getDependsOn();
dependsOn.add(toVertex);
fromVertex.setDependsOn(dependsOn);
return true;
}
}