Graphs
A graph is a non-linear data structure consisting of nodes (also called vertices) and edges. It is used to represent connections between different entities. Graphs are widely used in various applications such as social networks, recommendation systems, routing algorithms, and much more.
In a graph, nodes represent entities and edges represent the relationships between those entities. The relationships can be many-to-many, one-to-many, or even one-to-one.
Graphs can be classified into two main types: directed graphs and undirected graphs. In a directed graph, the edges have a direction, while in an undirected graph, the edges do not have a direction.
Common Operations
- Add Vertex: Adding a new vertex/node to the graph.
- Add Edge: Connecting two vertices/nodes with an edge.
- Remove Vertex: Removing a vertex/node from the graph.
- Remove Edge: Removing an edge between two vertices/nodes.
- Traverse: Visiting all the vertices/nodes in the graph.
Graph Traversal
Graph traversal is the process of visiting all the vertices/nodes in a graph. There are two commonly used algorithms for graph traversal:
- Breadth-First Search (BFS): This algorithm explores all the vertices at the same level before moving to the next level.
- Depth-First Search (DFS): This algorithm explores as far as possible along each branch before backtracking.
Here's an example of how to represent and traverse a graph in Java:
1{code}
xxxxxxxxxx
}
class Graph {
private int V;
private LinkedList<Integer>[] adjacencyList;
public Graph(int v) {
V = v;
adjacencyList = new LinkedList[v];
for(int i=0; i<v; ++i) {
adjacencyList[i] = new LinkedList<Integer>();
}
}
public void addEdge(int v, int w) {
adjacencyList[v].add(w);
}
public void BFS(int start) {
boolean[] visited = new boolean[V];
LinkedList<Integer> queue = new LinkedList<Integer>();
visited[start] = true;
queue.add(start);
while(queue.size() != 0) {
start = queue.poll();
System.out.print(start + " ");
Iterator<Integer> i = adjacencyList[start].listIterator();
while(i.hasNext()) {