What are Nodes and Edges?
In a graph, each node represents an entity or an object. For example, in a social network graph, each node can represent a person. Nodes are connected to other nodes through edges, which indicate the relationship or connection between the entities.
Types of Graphs
There are different types of graphs depending on how the nodes and edges are structured:
- Undirected Graph: In an undirected graph, the edges have no specific direction. The relationship between two nodes is bidirectional.
- Directed Graph (Digraph): In a directed graph, each edge has a specific direction.
The relationship between two nodes is unidirectional.
- Weighted Graph: In a weighted graph, each edge has an associated weight or cost. This weight can represent various factors such as distance or time.
An adjacency matrix is a two-dimensional array that represents the connections between nodes. Each cell in the matrix indicates whether there is an edge between two nodes. If there is an edge, the value can be set to 1 or any other appropriate value to represent its weight.
<script> // Example adjacency matrix for a graph with 4 nodes const adjacencyMatrix = [ [0, 1, 1, 0], // Node 0 is connected to Node 1 and Node 2 [1, 0, 0, 1], // Node 1 is connected to Node 0 and Node 3 [1, 0, 0, 0], // Node 2 is connected to Node 0 [0, 1, 0, 0] // Node 3 is connected to Node
An adjacency list represents the connections between nodes using an array of linked lists or arrays. Each node in the graph has a list that contains its adjacent nodes.
<script> // Example adjacency list for a graph with four nodes const adjacencyList = [ [1,2], //Node-0 is connected to Node-1 and Node-2 , //Node-1 is connected to Node-3 , //Node-2 has no connections  //Node-3 is connected to Node-1 ];
Graph traversal refers to visiting all the nodes in a graph. There are two commonly used algorithms for traversing graphs:
- Breadth-First Search (BFS): BFS explores all the vertices of a particular level before moving on to the next level. It uses a queue data structure.
- Depth-First Search (DFS): DFS explores as far as possible along each branch before backtracking. It uses a stack or recursion.