-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraph.java
More file actions
74 lines (64 loc) · 1.76 KB
/
Graph.java
File metadata and controls
74 lines (64 loc) · 1.76 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
/**
* Defines the Graph class.
*/
package graph;
import java.util.ArrayList;
import java.util.HashMap;
// Graph class.
public class Graph {
int[][] adjList;
// Hash table to store nodes by index.
public HashMap<Integer, Node> nodesByIndex = new HashMap<Integer, Node>();
/**
* Constructor, assigning parameters to class properties and keeping
* a HashMap of all nodes.
* @param adjList Adjustment list: two params for no edge weights,
* three params for edges with weight.
*/
public Graph(int[][] adjList) {
this.adjList = adjList;
for (int[] edge : adjList) {
Node from = nodesByIndex.get(edge[0]);
if (from == null) {
from = addNodeWithIndex(edge[0]);
}
int toIndex = edge[1], cost = 0;
if (edge.length == 3) {
toIndex = edge[2];
cost = edge[1];
}
Node to = nodesByIndex.get(toIndex);
if (to == null) {
to = addNodeWithIndex(toIndex);
}
Edge e = new Edge(from, to, cost);
}
}
/**
* Creates and adds new node with a specified index.
* @param index The index of the new node.
* @return The added node.
*/
public Node addNodeWithIndex(int index) {
Node n = new Node(index);
nodesByIndex.put(index, n);
return n;
}
/**
* Gets all neighbors indexex in an ArrayList.
* @param index The index of the node to get neighbors from.
* @return Array of all neighbor index or an empty array.
*/
public ArrayList<Integer> getNeighborIndexes(int index) {
ArrayList<Integer> result = new ArrayList<Integer>();
Node a = nodesByIndex.get(index);
if (a == null) {
return result;
}
ArrayList<Node> arr = a.getNeighbors();
for (Node n : arr) {
result.add(n.index);
}
return result;
}
}