Graph Basics
What is a Graph?
A graph is a fundamental data structure in computer science that consists of a set of vertices (or nodes) and a set of edges connecting these vertices. Graphs are powerful tools for representing relationships and connections between different entities.
Key Components of a Graph
Vertices
Vertices represent individual elements or objects in a graph. Each vertex can store specific data or information.
Edges
Edges are connections between vertices that represent relationships or links between different elements.
Types of Graphs
Graph Type |
Description |
Characteristics |
Directed Graph |
Edges have a specific direction |
One-way relationships |
Undirected Graph |
Edges have no specific direction |
Bidirectional connections |
Weighted Graph |
Edges have associated weights |
Represents cost or distance |
Graph Representation
graph TD
A[Vertex A] --> B[Vertex B]
A --> C[Vertex C]
B --> D[Vertex D]
C --> D
Adjacency Matrix
A 2D array where rows and columns represent vertices, and values indicate edge connections.
Adjacency List
A collection of lists where each vertex has a list of its connected vertices.
Example Graph Implementation in Java
import java.util.*;
class Graph {
private Map<Integer, List<Integer>> adjacencyList;
public Graph() {
adjacencyList = new HashMap<>();
}
public void addVertex(int vertex) {
adjacencyList.putIfAbsent(vertex, new ArrayList<>());
}
public void addEdge(int source, int destination) {
adjacencyList.get(source).add(destination);
}
}
Common Graph Algorithms
- Depth-First Search (DFS)
- Breadth-First Search (BFS)
- Shortest Path Algorithms
- Minimum Spanning Tree
Practical Applications
Graphs are used in various domains:
- Social networks
- Transportation networks
- Computer networks
- Recommendation systems
Learning graphs is an essential skill for developers using LabEx's advanced programming courses.