A Graph is a non-linear data structure consisting of vertices (nodes) and edges that connect these vertices. Graphs are used to represent networks, relationships, and connections between objects.
Vertex (Node)
Edge
Degree
Directed Graph (Digraph)
Undirected Graph
Weighted Graph
Cyclic/Acyclic Graph
Adjacency Matrix
Adjacency List
Operation | Adjacency Matrix | Adjacency List |
---|---|---|
Add Vertex | O(V²) | O(1) |
Add Edge | O(1) | O(1) |
Remove Vertex | O(V²) | O(V + E) |
Remove Edge | O(1) | O(E) |
Query | O(1) | O(V) |
Space Complexity | O(V²) | O(V + E) |
package main
import "fmt"
// Graph structure using adjacency list
type Graph struct {
vertices map[int][]int
}
// Create new graph
func NewGraph() *Graph {
return &Graph{
vertices: make(map[int][]int),
}
}
// Add vertex
func (g *Graph) AddVertex(v int) {
if _, exists := g.vertices[v]; !exists {
g.vertices[v] = []int{}
}
}
// Add edge
func (g *Graph) AddEdge(v1, v2 int) {
g.vertices[v1] = append(g.vertices[v1], v2)
g.vertices[v2] = append(g.vertices[v2], v1) // For undirected graph
}
// DFS traversal
func (g *Graph) DFS(start int, visited map[int]bool) {
if visited == nil {
visited = make(map[int]bool)
}
visited[start] = true
fmt.Printf("%d ", start)
for _, neighbor := range g.vertices[start] {
if !visited[neighbor] {
g.DFS(neighbor, visited)
}
}
}
func main() {
graph := NewGraph()
// Add vertices
for i := 0; i < 5; i++ {
graph.AddVertex(i)
}
// Add edges
graph.AddEdge(0, 1)
graph.AddEdge(0, 2)
graph.AddEdge(1, 3)
graph.AddEdge(2, 4)
// Perform DFS
fmt.Println("DFS Traversal:")
graph.DFS(0, nil)
}
import java.util.*;
public class Graph {
private Map<Integer, List<Integer>> adjacencyList;
public Graph() {
adjacencyList = new HashMap<>();
}
// Add vertex
public void addVertex(int vertex) {
adjacencyList.putIfAbsent(vertex, new ArrayList<>());
}
// Add edge
public void addEdge(int source, int destination) {
adjacencyList.get(source).add(destination);
adjacencyList.get(destination).add(source); // For undirected graph
}
// BFS traversal
public void BFS(int start) {
Set<Integer> visited = new HashSet<>();
Queue<Integer> queue = new LinkedList<>();
visited.add(start);
queue.add(start);
while (!queue.isEmpty()) {
int vertex = queue.poll();
System.out.print(vertex + " ");
for (int neighbor : adjacencyList.get(vertex)) {
if (!visited.contains(neighbor)) {
visited.add(neighbor);
queue.add(neighbor);
}
}
}
}
public static void main(String[] args) {
Graph graph = new Graph();
// Add vertices
for (int i = 0; i < 5; i++) {
graph.addVertex(i);
}
// Add edges
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 3);
graph.addEdge(2, 4);
// Perform BFS
System.out.println("BFS Traversal:");
graph.BFS(0);
}
}
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def add_edge(self, u, v):
self.graph[u].append(v)
self.graph[v].append(u) # For undirected graph
def bfs(self, start):
visited = set()
queue = deque([start])
visited.add(start)
while queue:
vertex = queue.popleft()
print(vertex, end=" ")
for neighbor in self.graph[vertex]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
def dfs(self, vertex, visited=None):
if visited is None:
visited = set()
visited.add(vertex)
print(vertex, end=" ")
for neighbor in self.graph[vertex]:
if neighbor not in visited:
self.dfs(neighbor, visited)
if name == "__main__":
g = Graph() # Add edges
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 3)
g.add_edge(2, 4)
print("BFS Traversal:")
g.bfs(0)
print("\nDFS Traversal:")
g.dfs(0)
Traversal Algorithms
Shortest Path Algorithms
Minimum Spanning Tree
Cycle Detection
Social Networks
Transportation
Computer Networks
Biology
Choosing Representation
Algorithm Selection
Performance Optimization
Memory Management
Performance Issues
Graph Validation
Graphs are powerful data structures used in numerous real-world applications. Understanding graph concepts and algorithms is essential for solving complex problems in various domains like social networks, transportation, and computer networks. The choice of implementation and algorithms depends on specific requirements such as graph size, density, and performance constraints.