0% found this document useful (0 votes)
5 views

Graph

The document provides an overview of graph data structures, including definitions, components, types, representations, and basic operations. It highlights the differences between graphs and trees, discusses traversal methods (BFS and DFS), and outlines their advantages and disadvantages. Additionally, it covers applications of both traversal methods in various fields.

Uploaded by

Ishavdeep Kaur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Graph

The document provides an overview of graph data structures, including definitions, components, types, representations, and basic operations. It highlights the differences between graphs and trees, discusses traversal methods (BFS and DFS), and outlines their advantages and disadvantages. Additionally, it covers applications of both traversal methods in various fields.

Uploaded by

Ishavdeep Kaur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

GRAPH

Graph Data Structure is a collection of nodes connected by edges. It’s used


to represent relationships between different entities. Graph algorithms are
methods used to manipulate and analyze graphs, solving various problems
like finding the shortest path or detecting cycles.

Graph is a non-linear data structure consisting of vertices and edges. The


vertices are sometimes also referred to as nodes and the edges are lines or arcs
that connect any two nodes in the graph. More formally a Graph is composed of
a set of vertices( V ) and a set of edges( E ). The graph is denoted by G(V, E).
Imagine a game of football as a web of connections, where players are the nodes
and their interactions on the field are the edges. This web of connections is
exactly what a graph data structure represents, and it’s the key to unlocking
insights into team performance and player dynamics in sports.

Components of Graph Data Structure


• 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.
Types Of Graphs in Data Structure and Algorithms

1. Null Graph
A graph is known as a null graph if there are no edges in the graph.

2. Trivial Graph
Graph having only a single vertex, it is also the smallest graph possible.

3. Undirected Graph
A graph in which edges do not have any direction. That is the nodes are
unordered pairs in the definition of every edge.
4. Directed Graph
A graph in which edge has direction. That is the nodes are ordered pairs in the
definition of every edge.

5. Connected Graph
The graph in which from one node we can visit any other node in the graph is
known as a connected graph.

6. Disconnected Graph
The graph in which at least one node is not reachable from a node is known as
a disconnected graph.

7. Regular Graph
The graph in which the degree of every vertex is equal to K is called K regular
graph.

8. Complete Graph
The graph in which from each node there is an edge to each other node.

9. Cycle Graph
The graph in which the graph is a cycle in itself, the minimum value of degree
of each vertex is 2.

10. Cyclic Graph

A graph containing at least one cycle is known as a Cyclic graph.

11. Directed Acyclic Graph


A Directed Graph that does not contain any cycle.

12. Bipartite Graph


A graph in which vertex can be divided into two sets such that vertex in each
set does not contain any edge between them.
13. Weighted Graph

• A graph in which the edges are already specified with suitable


weight is known as a weighted graph.
• Weighted graphs can be further classified as directed weighted
graphs and undirected weighted graphs.

Representation of Graph Data Structure:

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.
Example : To implement a Graph we will use an Adjacency Matrix, like the one
below.

To store data for each vertex, in this case the letters A, B, C, and D, the data is
put in a separate array that matches the indexes in the adjacency matrix, like this:

Adjacency List Representation of Graph:


This graph is represented as a collection of linked lists. There is an array of
pointer which points to the edges connected to that vertex.
Basic Operations on Graph Data Structure:

Below are the basic operations on the graph:

1.Insertion or Deletion of Nodes in the graph


2.Insertion or Deletion of Edges in the graph
3.Searching in Graph Data Structure- Search an entity in the graph.
4.Traversal of Graph Data Structure- Traversing all the nodes in the graph.

Difference between Tree and Graph:

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.
Advantages of Graph Data Structure:

• Graph Data Structure used to represent a wide range of relationships


as we do not have any restrictions like previous data structures (Tree
cannot have loops and have to be hierarchical. Arrays, Linked List, etc
are linear)
• They can be used to model and solve a wide range of problems,
including pathfinding, data clustering, network analysis, and machine
learning.
• Any real world problem where we certain set of items and relations
between them can be easily modeled as a graph and a lot of standard
graph algorithms like BFS, DFS, Spanning Tree, Shortest Path,
Topological Sorting and Strongly Connected
• Graph Data Structure can be used to represent complex data
structures in a simple and intuitive way, making them easier to
understand and analyze.

Disadvantages of Graph Data Structure:


• Graph Data Structure can be complex and difficult to understand,
especially for people who are not familiar with graph theory or related
algorithms.
• Creating and manipulating graphs can be computationally expensive,
especially for very large or complex graphs.
• Graph algorithms can be difficult to design and implement correctly,
and can be prone to bugs and errors.
• Graph Data Structure can be difficult to visualize and analyze,
especially for very large or complex graphs, which can make it
challenging to extract meaningful insights from the data.

A Graph is a non-linear data structure consisting of nodes and edges. The nodes
are sometimes also referred to as vertices and the edges are lines or arcs that
connect any two nodes in the graph.

The basic properties of a graph include:

1. Vertices (nodes): The points where edges meet in a graph are known
as vertices or nodes. A vertex can represent a physical object, concept,
or abstract entity.
2. Edges: The connections between vertices are known as edges. They
can be undirected (bidirectional) or directed (unidirectional).
3. Weight: A weight can be assigned to an edge, representing the cost or
distance between two vertices. A weighted graph is a graph where the
edges have weights.
4. Degree: The degree of a vertex is the number of edges that connect to
it. In a directed graph, the in-degree of a vertex is the number of edges
that point to it, and the out-degree is the number of edges that start
from it.
5. Path: A path is a sequence of vertices that are connected by edges. A
simple path does not contain any repeated vertices or edges.
6. Cycle: A cycle is a path that starts and ends at the same vertex. A
simple cycle does not contain any repeated vertices or edges.
7. Connectedness: A graph is said to be connected if there is a path
between any two vertices. A disconnected graph is a graph that is not
connected.
8. Planarity: A graph is said to be planar if it can be drawn on a plane
without any edges crossing each other.
9. Bipartiteness: A graph is said to be bipartite if its vertices can be
divided into two disjoint sets such that no two vertices in the same set
are connected by an edge.

What is Graph?

A graph data structure is a collection of nodes (also called vertices)


and edges that connect them. Nodes can represent entities, such as people,
places, or things, while edges represent relationships between those entities.
Graphs are used to model a wide variety of real-world systems, such as social
networks, transportation networks, and computer networks.

What is Tree?

A tree data structure is a hierarchical data structure that consists of nodes


connected by edges. Each node can have multiple child nodes, but only one
parent node. The topmost node in the tree is called the root node.
Trees are often used to represent hierarchical data, such as file systems, XML
documents, and organizational charts.

Difference Between Graph and Tree

Feature Graph Tree

A collection of nodes
A hierarchical data structure
(vertices) and edges,
consisting of nodes connected by
where edges connect
edges with a single root node.
Definition nodes.

Can have cycles (loops) No cycles; connected structure


and disconnected with exactly one path between
Structure components. any two nodes.

No root node; nodes


may have multiple Has a designated root node that
parents or no parents at has no parent.
Root Node all.

Parent-child relationship; each


Relationships between
Node node (except the root) has exactly
nodes are arbitrary.
Relationship one parent.

Each node can have any If there is n nodes then there


Edges number of edges. would be n-1 number of edges
Feature Graph Tree

Traversal can be
complex due to cycles Traversal is straightforward and
Traversal and disconnected can be done in linear time.
Complexity components.

Used in various Commonly used for hierarchical


scenarios like social data representation like file
networks, maps, systems, organization charts,
network optimization, HTML DOM, XML documents,
Application etc. etc.

Social networks, road


File systems, family trees, HTML
networks, computer
DOM structure.
Examples networks.
Graphs Traversal

To traverse a Graph means to start in one vertex, and go along the edges to visit
other vertices until all vertices, or as many as possible, have been visited.

The two most common ways a Graph can be traversed are:

• Depth First Search (DFS)


• Breadth First Search (BFS)

DFS is usually implemented using a Stack or by the use of recursion (which


utilizes the call stack), while BFS is usually implemented using a Queue.

Breadth First Search Traversal

Breadth First Search visits all adjacent vertices of a vertex before visiting
neighboring vertices to the adjacent vertices. This means that vertices with the
same distance from the starting vertex are visited before vertices further away
from the starting vertex are visited.

Steps:

1. Put the starting vertex into the queue.


2. For each vertex taken from the queue, visit the vertex, then put all unvisited
adjacent vertices into the queue.
3. Continue as long as there are vertices in the queu
Depth First Search Traversal

Depth First Search is said to go "deep" because it visits a vertex, then an adjacent
vertex, and then that vertex' adjacent vertex, and so on, and in this way the
distance from the starting vertex increases for each recursive iteration.

Steps

1. Start DFS traversal on a vertex.


2. Do a recursive DFS traversal on each of the adjacent vertices as long as
they are not already visited.

Graph Traversal

1.BFS

2.DFS
Applications of Breadth First Search:
Shortest Path and Minimum Spanning Tree for unweighted graph:
Minimum Spanning Tree for weighted graphs:
Peer-to-Peer Networks
Crawlers in Search Engines:
Social Networking Websites
GPS Navigation systems
Broadcasting in Network
In Garbage Collection
Cycle detection in undirected graph:
Ford–Fulkerson algorithm
Path Finding
Finding all nodes within one connected component
Network Security
Connected Component
Topological sorting
Image processing:
Recommender systems:

Applications of Depth First Search:


Detecting cycle in a graph:
Path Finding:
Topological Sorting
Finding Strongly Connected Components of a graph
Solving puzzles with only one solution
Web crawlers.
Model checking
Backtracking
DFS Applications BFS Applications

Cycle detection in graphs Finding the shortest path in unweighted


graphs

Finding connected components in a graph Level-order traversal in trees

Solving puzzles like Sudoku, N-Queens Web crawling (breadth-first)


(backtracking)

Topological sorting in Directed Acyclic Graphs Social network analysis (finding the
(DAGs) shortest path between users)

Finding strongly connected components Finding nodes at a specific level in a


(Tarjan's/Kosaraju's algorithm) graph or tree

Maze solving (exploring all paths) Minimum moves in a game or puzzle


(e.g., 8-puzzle)

Web crawling (depth-first) Friend suggestion algorithms in social


networks

Tree traversal (pre-order, in-order, post-order) Finding the shortest path in a maze

Pathfinding in games (exploring all paths) Level-by-level exploration in AI game


design
Advantages of Breadth First Search:
• BFS will never get trapped exploring the useful path forever.
• If there is a solution, BFS will definitely find it.
• If there is more than one solution then BFS can find the minimal one
that requires less number of steps.
• Low storage requirement – linear with depth.
• Easily programmable.

Disadvantages of Breadth First Search:


The main drawback of BFS is its memory requirement. Since each level of the
graph must be saved in order to generate the next level and the amount of
memory is proportional to the number of nodes stored the space complexity of
BFS is O(bd ), where b is the branching factor(the number of children at each
node, the outdegree) and d is the depth. As a result, BFS is severely space-bound
in practice so will exhaust the memory available on typical computers in a
matter of minutes.

Advantages of Depth First Search:

• Memory requirement is only linear with respect to the search graph.


This is in contrast with breadth-first search which requires more space.
The reason is that the algorithm only needs to store a stack of nodes
on the path from the root to the current node.
• The time complexity of a depth-first Search to depth d and branching
factor b (the number of children at each node, the outdegree) is O(bd)
since it generates the same set of nodes as breadth-first search, but
simply in a different order. Thus practically depth-first search is time-
limited rather than space-limited.
• If depth-first search finds solution without exploring much in a path
then the time and space it takes will be very less.
• DFS requires less memory since only the nodes on the current path
are stored. By chance DFS may find a solution without examining
much of the search space at all.

Disadvantages of Depth First Search:

• The disadvantage of Depth-First Search is that there is a possibility


that it may down the left-most path forever. Even a finite graph can
generate an infinite solution to this problem is to impose a cutoff depth
on the search. Although ideal cutoff is the solution depth d and this
value is rarely known in advance of actually solving the problem. If
the chosen cutoff depth is less than d, the algorithm will fail to find a
solution, whereas if the cutoff depth is greater than d, a large price is
paid in execution time, and the first solution found may not be an
optimal one.
• Depth-First Search is not guaranteed to find the solution.
• And there is no guarantee to find a minimal solution, if more than
one solution.
Imp

Parameters BFS DFS

BFS stands for Breadth DFS stands for Depth First


Stands for First Search. Search.

BFS(Breadth First Search)


uses Queue data structure DFS(Depth First Search) uses
Data for finding the shortest Stack data structure.
Structure path.

DFS is also a traversal


BFS is a traversal
approach in which the
approach in which we first
traverse begins at the root
walk through all nodes on
node and proceeds through
the same level before
the nodes as far as possible
moving on to the next
until we reach the node with
level.
Definition no unvisited nearby nodes.

Conceptual BFS builds the tree level DFS builds the tree sub-tree
Difference by level. by sub-tree.

Approach It works on the concept of It works on the concept of


used FIFO (First In First Out). LIFO (Last In First Out).

BFS is more suitable for DFS is more suitable when


searching vertices closer to there are solutions away from
Suitable for the given source. source.

BFS is used in various DFS is used in various


applications such as applications such as acyclic
bipartite graphs, shortest graphs and finding strongly
paths, etc. If weight of connected components etc.
every edge is same, then There are many applications
Applications BFS gives shortest pat where both BFS and DFS can
Parameters BFS DFS

from source to every other be used like Topological


vertex. Sorting, Cycle Detection, etc

Difference between BFS and DFS


The following are the important differences between BFS and DFS ?

Key BFS DFS

BFS stands for Breadth First


Definition DFS stands for Depth First Search.
Search.

Data BFS uses a Queue to find the


structure DFS uses a Stack to find the shortest path.
shortest path.

BFS is better when target is


Source DFS is better when target is far from source.
closer to Source.

DFS is more suitable for decision tree. As with


As BFS considers all neighbor
Suitability for one decision, we need to traverse further to
so it is not suitable for decision
decision tree augment the decision. If we reach the
tree used in puzzle games.
conclusion, we won.

Speed BFS is slower than DFS. DFS is faster than BFS.

Time Complexity of BFS =


Time Time Complexity of DFS is also O(V+E) where
O(V+E) where V is vertices and
Complexity V is vertices and E is edges.
E is edges.

BFS requires more memory


Memory DFS requires less memory space.
space.

Tapping in In BFS, there is no problem of


In DFS, we may be trapped into infinite loops.
loops trapping into finite loops.

BFS is implemented using FIFO DFS is implemented using LIFO (Last In First
Principle
(First In First Out) principle. Out) principle.
DFS and BFS Time Complexity
Criteria BFS (Breadth-First Search) DFS (Depth-First Search)

Time Complexity O(V + E) O(V + E)

V = Number of O(V) O(V)


Vertices

E = Number of O(E) O(E)


Edges

Graph Type Applies to both directed and Applies to both directed and
undirected graphs undirected graphs

Traversal Strategy Level-by-level (breadth) Depth-wise traversal

Difference Between DFS and BFS


ind all the differences between DFS and BFS algorithms:

Criteria BFS (Breadth-First Search) DFS (Depth-First Search)

Traversal Method Explores all neighbors at the Explores as deep as possible


current level before moving to along one branch before
the next level. backtracking.

Data Structure Used Queue (FIFO) Stack (LIFO) or recursion stack.

Time Complexity O(V + E) (V = vertices, E = O(V + E) (V = vertices, E =


edges) edges)

Space Complexity O(V) (due to queue storing O(V) (due to recursion or


nodes at the current level) explicit stack)

Best for Finding the shortest path in an Exploring all possible paths or
unweighted graph. solving puzzles like mazes.
Use Case - Shortest path in unweighted - Solving maze or puzzle
graphs (like social networks, problems.
web crawlers). - Detecting cycles in graphs,
- Level-order traversal of trees. topological sorting.

Performance on Deep May require more memory for Efficient for deep graphs, as it
Graphs wide/deep graphs, as the traverses a single path at a
queue holds many nodes. time.

Performance on Wide Efficient for shallow/wide May require more memory for
Graphs graphs, as it processes level by wide graphs, as the recursion
level. stack can grow large.

Shortest Path Guaranteed to find the shortest Not guaranteed to find the
path in an unweighted graph. shortest path, but explores all
paths.

Pathfinding in Not suitable for weighted Not suitable for weighted graphs
Weighted Graphs graphs. (Dijkstra's or Bellman-Ford
should be used).

Cycle Detection Can detect cycles, but less Useful for detecting cycles in
commonly used for it. directed or undirected graphs.

Recursive/Iterative Iterative (uses a queue) Can be recursive (via recursion


stack) or iterative (using an
explicit stack).

Graph Representation Can be used with both Can be used with both
adjacency lists and matrices. adjacency lists and matrices.

Tree Traversal Used for level-order traversal in Used for pre-order, in-order, and
trees. post-order traversal in trees.

Backtracking No backtracking. Uses backtracking to explore


new branches.

Algorithm Type Greedy approach (explores Backtracking approach


level by level). (explores depth first).
Application in AI Used in algorithms like breadth- Used in algorithms like depth-
first search for game AI (level first search for solving constraint
exploration). satisfaction problems.

Example of Use Finding the shortest path from Exploring all possible paths to
a source to all nodes in an solve a maze
unweighted graph.

DFS vs BFS: Which is Faster

Neither DFS nor BFS is inherently faster than the other; both have the same time
complexity of O(V + E), where V is the number of vertices and E is the number
of edges.

However, BFS is faster for finding the shortest path in unweighted graphs, while
DFS can be faster when searching deeper paths without concern for the shortest
path. The speed depends on the specific problem and the structure of the graph.

DFS vs BFS For Shortest Path

For the shortest path in an unweighted graph, BFS is the better choice because it
explores nodes level by level, ensuring the shortest path is found. DFS does not
guarantee the shortest path, as it explores one path deeply before backtracking,
which may result in longer paths being found first.

You might also like