Graphs
Graphs are a versatile data structure that represents relationships between entities. In a graph, entities are represented by vertices or nodes, and relationships between them are represented by edges. Graphs can be used to model various real-world scenarios, such as social networks, transportation networks, and computer networks.
Graphs can be represented in different ways, depending on the problem at hand. One common representation is the adjacency list. An adjacency list stores each vertex as a key and its adjacent vertices as a list of values. Here's an example of creating and printing a graph using an adjacency list in Java:
1<<code>>
In this example, we create a graph with four vertices (A, B, C, D) and three edges (A-B, B-C, C-D). The Graph
class provides methods to add vertices, add edges, and print the graph. By using the adjacency list representation, we can efficiently traverse the graph and perform operations such as finding neighbors of a vertex or checking if two vertices are connected.
Understanding the basics of graphs and their representations is essential for solving graph-related problems and designing efficient algorithms.
xxxxxxxxxx
}
class Main {
public static void main(String[] args) {
// replace with your Java logic here
Graph graph = new Graph();
// Add vertices
graph.addVertex("A");
graph.addVertex("B");
graph.addVertex("C");
graph.addVertex("D");
// Add edges
graph.addEdge("A", "B");
graph.addEdge("B", "C");
graph.addEdge("C", "D");
// Print the graph
graph.printGraph();
}
}
class Graph {
Map<String, List<String>> graph;
public Graph() {
this.graph = new HashMap<>();
}
public void addVertex(String vertex) {