A graph is a non-linear data structure made up of vertices (nodes) and edges (connections) that represent relationships between objects. Unlike arrays or linked lists, graphs do not follow a sequential order. Example: On a map, each city is a vertex, and each road connecting two cities is an edge. This way, a graph represents how cities are linked.
Vertices: Vertices are the fundamental units of the graph. Sometimes, vertices are also known as vertex or nodes. Every node/vertex can be labeled or unlabelled.
Edges: Edges are drawn or used to connect two nodes of the graph. It can be ordered pair of nodes in a directed graph. Edges can connect any two nodes in any possible way. There are no rules. Sometimes, edges are also known as arcs. Every edge can be labelled/unlabelled.
A graph can be divided into multiple categories based on different properties such as edges, direction, connectivity and many others.
Based on weight :
1. Weighted Graphs
A weighted graph is a graph where each edge has a number (weight) that represents distance, cost, or time.
There are multiple ways to store a graph: The following are the most common representations.
Adjacency Matrix
Adjacency List
Adjacency Matrix Representation of Graph Data Structure:
In this method, the graph is stored in the form of the 2D matrix where rows and columns denote vertices. Each entry in the matrix represents the weight of the edge between those vertices.
matrix[i][j] = 1 if there is an edge between vertex i and vertex j. matrix[i][j] = 0 if there is no edge.
Tree is a restricted type of Graph Data Structure, just with some more rules. Every tree will always be a graph but not all graphs will be trees. Linked List, Trees, and Heaps all are special cases of graphs.
Traversal techniques are used to visit all the vertices of a graph systematically. These methods help to explore the graph completely and are useful for solving many graph-related problems.
Depth First Search (DFS):
Explores as far as possible along each branch before backtracking.