Building a Weighted Graph in Java
Representing Weighted Graphs in Java
In Java, you can represent a weighted graph using an adjacency matrix or an adjacency list. The choice between these two representations depends on the specific requirements of your application, such as the size of the graph, the frequency of edge updates, and the type of operations you need to perform.
Adjacency Matrix Representation
An adjacency matrix is a 2D array where each element represents the weight of the edge between two nodes. If there is no edge between two nodes, the corresponding element in the matrix is typically set to 0 or a large value (e.g., Integer.MAX_VALUE
) to indicate the absence of a connection.
Here's an example of how you can represent a weighted graph using an adjacency matrix in Java:
int[][] adjacencyMatrix = {
{0, 5, 3, 0},
{5, 0, 2, 1},
{3, 2, 0, 4},
{0, 1, 4, 0}
};
Adjacency List Representation
An adjacency list is a collection of linked lists or arrays, where each linked list or array represents the neighbors of a node and the weights of the corresponding edges.
Here's an example of how you can represent a weighted graph using an adjacency list in Java:
Map<Integer, List<WeightedEdge>> adjacencyList = new HashMap<>();
adjacencyList.put(0, new ArrayList<>(Arrays.asList(
new WeightedEdge(1, 5),
new WeightedEdge(2, 3)
)));
adjacencyList.put(1, new ArrayList<>(Arrays.asList(
new WeightedEdge(0, 5),
new WeightedEdge(2, 2),
new WeightedEdge(3, 1)
)));
adjacencyList.put(2, new ArrayList<>(Arrays.asList(
new WeightedEdge(0, 3),
new WeightedEdge(1, 2),
new WeightedEdge(3, 4)
)));
adjacencyList.put(3, new ArrayList<>(Arrays.asList(
new WeightedEdge(1, 1),
new WeightedEdge(2, 4)
)));
In this example, the WeightedEdge
class is a custom class that represents an edge with a source node, a destination node, and a weight.
Building a Weighted Graph in Java
To build a weighted graph in Java, you can use either the adjacency matrix or adjacency list representation, depending on your requirements. Here's an example of how you can create a weighted graph using the adjacency list representation:
public class WeightedGraph<T> {
private Map<T, List<WeightedEdge<T>>> adjacencyList;
public WeightedGraph() {
adjacencyList = new HashMap<>();
}
public void addVertex(T vertex) {
adjacencyList.putIfAbsent(vertex, new ArrayList<>());
}
public void addEdge(T source, T destination, double weight) {
if (!adjacencyList.containsKey(source)) {
addVertex(source);
}
if (!adjacencyList.containsKey(destination)) {
addVertex(destination);
}
adjacencyList.get(source).add(new WeightedEdge<>(destination, weight));
}
// Other methods, such as getNeighbors, getWeight, etc.
}
In this example, the WeightedGraph
class uses a Map
to store the adjacency list representation of the weighted graph. The addVertex
method adds a new vertex to the graph, and the addEdge
method adds a new weighted edge between two vertices.