Graph
A graph is a data structure that consists of a set of nodes (also called vertices) and a set of edges that connect pairs of nodes. Graphs can be directed or undirected, depending on whether the edges have a direction associated with them. They are used to represent various types of relationships and connections, such as social networks, transportation systems, and communication networks.
Types of Graphs
- Directed Graph (Digraph): A graph where each edge has a direction, indicating a one-way relationship between nodes.
- Undirected Graph: A graph where edges have no direction, indicating a two-way relationship between nodes.
- Weighted Graph: A graph where each edge has an associated weight or cost, representing the strength or distance of the connection between nodes.
- Unweighted Graph: A graph where edges do not have associated weights or costs.
- Connected Graph: A graph where there is a path between every pair of nodes.
- Disconnected Graph: A graph where there are isolated nodes or groups of nodes that are not connected to the rest of the graph.
- Cyclic Graph: A graph that contains at least one cycle, which is a path that starts and ends at the same node.
- Acyclic Graph: A graph that does not contain any cycles.
Graph Representation
- Adjacency Matrix: A 2D array where the value at row i and column j indicates the presence or weight of an edge between nodes i and j.
- Adjacency List: A list where each node has a list of its adjacent nodes, along with the weights of the edges if applicable.
- Edge List: A list of all edges in the graph, where each edge is represented as a pair of nodes (and optionally the weight).
Graph Traversal
Graph traversal refers to the process of visiting each node in a graph in a specific order. The common graph traversal methods include:
- Depth-First Search (DFS): A traversal method that explores as far as possible along each branch before backtracking. It can be implemented using recursion or a stack.
- Breadth-First Search (BFS): A traversal method that explores all the neighbors of a node before moving on to the neighbors’ neighbors. It can be implemented using a queue.
- Dijkstra’s Algorithm: A traversal method used to find the shortest path between nodes in a weighted graph.
- A* Search Algorithm: A traversal method that uses heuristics to find the shortest path between nodes in a weighted graph, often used in pathfinding and graph traversal.
- Topological Sort: A traversal method used to order the nodes of a directed acyclic graph (DAG) in a linear sequence based on their dependencies.
Graph Example
1
2
3
4
5A
/ \
B C
/ \ \
D E F
1 | class Graph: |





