Graph Data Structure: Definition, Example, and Uses
graph is a data structure made of nodes (also called vertices) connected by edges. It models relationships between items, like a map of cities connected by roads or friends connected on social media.How It Works
A graph consists of points called nodes and lines called edges that connect pairs of nodes. Think of nodes as places on a map and edges as roads linking those places. Each edge shows a relationship or connection between two nodes.
Graphs can be directed, where edges have a direction (like one-way streets), or undirected, where edges go both ways (like two-way streets). They can also have weights, which are numbers showing the cost or distance of traveling an edge.
This structure helps represent complex networks such as social connections, computer networks, or routes in transportation.
Example
This example shows a simple undirected graph using a dictionary to store nodes and their connected neighbors.
graph = {
'A': ['B', 'C'],
'B': ['A', 'D'],
'C': ['A', 'D'],
'D': ['B', 'C']
}
for node, neighbors in graph.items():
print(f"Node {node} is connected to: {', '.join(neighbors)}")When to Use
Graphs are useful when you need to represent and analyze relationships between objects. Use graphs for:
- Social networks to show friendships or followers.
- Maps and navigation systems to find routes between locations.
- Computer networks to model connections between devices.
- Recommendation systems to link users with products or content.
Graphs help solve problems like finding the shortest path, detecting cycles, or grouping related items.
Key Points
- A graph has nodes (vertices) and edges (connections).
- Edges can be directed or undirected.
- Graphs can have weights to show cost or distance.
- They model complex relationships in many fields.
- Graphs are flexible and powerful for network problems.