Graph
Graph
1. Definition of Graph
A graph is a non-linear data structure that consists of a collection of nodes (vertices) and a collection of
edges connecting pairs of nodes. Graphs are used to represent various real-world problems like social
networks, transportation networks, and web pages.
Edges (Arcs): The connections between the nodes. Each edge can be directed (one-way) or
undirected (two-way).
Directed Graph (Digraph): In a directed graph, edges have a direction, i.e., they go from one
vertex to another.
Undirected Graph: In an undirected graph, edges have no direction; they simply connect two
vertices.
2. Features of Graphs
Cyclic/Acyclic: A graph may contain cycles (paths where the start and end are the same) or may
not.
3. Operations on Graphs
6. DFS (Depth-First Search): Traverses the graph deeply, visiting one vertex before backtracking.
7. Shortest Path: Finds the shortest path between two vertices (e.g., Dijkstra’s algorithm).
8. Cycle Detection: Detects whether a cycle exists in the graph.
Pros:
Flexible Representation: Graphs can represent complex relationships like social networks, roads,
etc.
Variety of Applications: Can be used for shortest path, network flow, resource allocation, etc.
Cons:
Memory Overhead: Graphs can consume more memory, especially when using adjacency
matrices for sparse graphs.
Harder to Implement: Graphs often require more careful handling in terms of structure and
algorithms.
Example Java Code for Graph
Let's implement a simple graph using an adjacency list in Java and include BFS and DFS traversal
operations.
import java.util.*;
class Graph {
public Graph() {
visited.add(start);
queue.add(start);
while (!queue.isEmpty()) {
if (!visited.contains(neighbor)) {
visited.add(neighbor);
queue.add(neighbor);
System.out.println();
DFSUtil(start, visited);
System.out.println();
visited.add(vertex);
System.out.print(vertex + " ");
if (!visited.contains(neighbor)) {
DFSUtil(neighbor, visited);
System.out.println();
// Add vertices
graph.addVertex(0);
graph.addVertex(1);
graph.addVertex(2);
graph.addVertex(3);
graph.addVertex(4);
// Add edges
graph.addEdge(0, 1);
graph.addEdge(0, 4);
graph.addEdge(1, 2);
graph.addEdge(1, 3);
graph.addEdge(2, 4);
System.out.println("Graph:");
graph.printGraph();
// BFS traversal
graph.BFS(0);
// DFS traversal
graph.DFS(0);
}
Explanation of the Code:
1. Graph Class:
o addEdge(): Adds an edge between two vertices. This creates an undirected edge by
adding the connection in both directions.
2. Main Class:
o BFS and DFS Traversal: Both BFS and DFS algorithms are tested starting from vertex 0.
Output:
Graph:
0 -> 1 4
1 -> 0 2 3
2 -> 1 4
3 -> 1
4 -> 0 2
01423
01243