-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathUndirectedGraphs.java
91 lines (74 loc) · 1.8 KB
/
UndirectedGraphs.java
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
88
89
90
91
package algorithms;
import java.util.*;
/**
* Implementation of undirected graph represented using adjacency list.
*
* @author joeytawadrous
*/
public final class UndirectedGraphs<T> implements Iterable<T>
{
private final Map<T, Set<T>> graph = new HashMap<T, Set<T>>();
public boolean addNode(T node)
{
if (graph.containsKey(node)) { return false; }
graph.put(node, new HashSet<T>());
return true;
}
public void addEdge(T start, T dest)
{
if (!graph.containsKey(start) || !graph.containsKey(dest))
{
System.out.println("No such nodes in the graph.");
}
else
{
graph.get(start).add(dest);
graph.get(dest).add(start);
}
}
public void removeEdge(T start, T dest)
{
if (!graph.containsKey(start) || !graph.containsKey(dest))
{
System.out.println("No such nodes in the graph.");
}
else
{
graph.get(start).remove(dest);
graph.get(dest).remove(start);
}
}
public boolean isEdgeExists(T start, T end)
{
if (!graph.containsKey(start) || !graph.containsKey(end))
{
System.out.println("No such nodes in the graph.");
}
return graph.get(start).contains(end);
}
public Set<T> getNeighbors(T node)
{
Set<T> neighbors = graph.get(node);
if (neighbors == null)
{
System.out.println("No such nodes in the graph.");
}
return Collections.unmodifiableSet(neighbors);
}
public Iterator<T> iterator()
{
return graph.keySet().iterator();
}
public Iterable<T> getNodes()
{
return graph.keySet();
}
public int size()
{
return graph.size();
}
public boolean isEmpty()
{
return graph.isEmpty();
}
}