forked from techpanja/interviewproblems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnDirectedGraph.java
More file actions
87 lines (73 loc) · 2.25 KB
/
UnDirectedGraph.java
File metadata and controls
87 lines (73 loc) · 2.25 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
81
82
83
84
85
86
87
package graphs.graph;
import java.util.List;
/**
* UnDirected AbstractGraph.
* User: rpanjrath
* Date: 10/24/13
* Time: 5:58 PM
*/
public class UnDirectedGraph extends AbstractGraph {
private Vertex[] vertexes;
private int maxSize;
private int currentSize;
public UnDirectedGraph(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 + "\" and vice-versa");
System.out.println();
return false;
}
List<Vertex> starDependsOn = fromVertex.getDependsOn();
starDependsOn.add(toVertex);
List<Vertex> endDependsOn = toVertex.getDependsOn();
endDependsOn.add(fromVertex);
fromVertex.setDependsOn(starDependsOn);
toVertex.setDependsOn(endDependsOn);
return true;
}
}