Department of Informatics
Faculty of Industrial Engineering
Universitas Pembangunan Nasional “Veteran” Yogyakarta
Data
Structure
Andi Nurkholis, S.Kom., M.Kom.
Graph: Concept &
Implementation
November 24, 2025
Definition of Graph
Graph is an important data structure that represents relationships between
nodes through edges, either directed or undirected. Graphs are widely used in
various fields such as computer networks, transportation, social networks,
data analysis, logistics planning, and complex system optimization.
More formally, a graph can be defined as an ordered pair (G = (V, E)), where:
ü (V) is the set containing the vertices or nodes in the graph.
ü (E) is the set containing the edges that connect pairs of vertices.
Component of
Graph
1. Vertex (Node)
2. Edge
3. Degree
Component of Graph
1. Vertex (Node): The fundamental entity of a graph representing an object or
point with a unique identity, such as a city in a transportation network or a
user in a social network.
2. Edge: The connection between nodes, which can be directed or undirected,
and may carry weights such as distance, cost, or time.
3. Degree: The number of edges connected to a node. In an undirected graph,
the degree indicates the number of direct connections of that node. In a
directed graph, there are two types of degrees: a) In-degree: The number of
edges entering the node; b) Out-degree: The number of edges leaving the
node.
Types of
Graph
1. Undirected Graph)
2. Directed Graph)
3. Weighted Graph
4. Disconnected Graph
5. Connected Graph
Types of
Graph
6. Cyclic Graph
7. Acyclic Graph
8. Tree
9. Bipartite Graph
Types of Graph
1. Undirected Graph: The edges have no direction, meaning the relationship
between two vertices is mutual. If vertex A is connected to vertex B, then B
is also automatically connected to A.
2. Directed Graph: Each edge has a specific direction indicating a one-way
relationship between vertices. If there is an edge from A to B, the connection
does not automatically exist from B to A.
3. Weighted Graph: Each edge carries a specific weight or value that can
represent distance, time, or cost between vertices. This type of graph is
commonly used in communication networks and transportation systems.
Types of Graph
4. Disconnected Graph: A graph is said to be disconnected if there exists at
least one vertex that has no direct connection with other vertices.
5. Connected Graph: A graph is said to be connected if every pair of vertices
can be linked by a path.
6. Cyclic Graph: A graph is said to be cyclic if it contains a cycle, meaning a
path that starts and ends at the same vertex.
Types of Graph
7. Acyclic Graph: A graph is said to be acyclic if it contains no cycles. One
common example of an acyclic graph is a tree.
8. Tree Graph: A tree is a connected graph with no cycles, consisting of a root
node and branch nodes. Trees possess specific properties that simplify
computation and structural analysis.
9. Bipartite Graph: A bipartite graph is a graph whose vertices are divided into
two distinct sets, where each edge connects a vertex from the first set to one
in the second set, with no edges connecting vertices within the same set.
Representation of Graph
To store and operate on graphs efficiently, we need a memory-efficient
representation method. There are two common approaches used to represent
graphs in memory:
ü Adjacency Matrix: A two-dimensional square matrix that shows the
relationships between vertices in a graph. A value of 1 (or a weight) indicates
the presence of an edge, while 0 means no connection. Its advantage is fast
access time, but the drawback is high space usage of O(V²) for sparse
graphs. Example of an adjacency matrix for a directed graph:
A B C D
A 0 1 0 0
B 0 0 1 0
C 1 0 0 1
D 0 0 1 0
Representation of Graph
ü Adjacency list: Struktur data yang lebih hemat memori daripada adjacency
matrix, terutama pada graf yang jarang. Pada adjacency list, setiap simpul
memiliki daftar yang berisi simpul-simpul yang terhubung langsung
dengannya. Kelebihan: Lebih hemat memori, terutama pada graf yang jarang
(sparse graph). Kekurangan: Tidak efisien untuk memeriksa keberadaan sisi
antara dua simpul, karena memerlukan pencarian dalam daftar. Contoh
adjacency list untuk graf berarah:
A -> B
B -> C
C -> A, D
D -> C
Basic Operation of
Graph
1. Vertex Insertion
2. Edge Insertion
3. Vertex Deletion
4. Edge Deletion
5. Pathfinder
Vertex Insertion Operation
1. Determine the new vertex to be added, including its unique identifier.
2. Check whether the vertex already exists to prevent duplication.
3. Add it to the graph data structure:
ü Adjacency List: Create an empty list for the new vertex.
ü Adjacency Matrix: Add a new row and column initialized with 0.
4. Update the total number of vertices in the graph.
5. Verify the vertex addition to ensure the new node has been successfully
added.
Edge Insertion Operation
1. Determine the two vertices to be connected by the new edge.
2. Check existence of both vertices to ensure they are present in the graph.
3. Add the edge according to the type of graph:
ü Undirected Graph: Add connections in both directions (A→B and B→A).
ü Directed Graph: Add a one-way connection (e.g., A→B).
4. If the graph is weighted, also include the weight value (e.g., distance, time).
5. Update the data structure with the new connection.
6. Verify the addition to ensure the new edge has been successfully created.
Vertex Deletion Operation
1. Determine the vertex to be deleted based on its unique identifier.
2. Check the existence of the vertex to ensure it is present in the graph.
3. Remove all edges connected to that vertex:
ü Adjacency List: Remove it from all neighbor lists.
ü Adjacency Matrix: Delete the corresponding row and column.
4. Remove the vertex from the graph’s data structure.
5. Update the total number of vertices and verify that the deletion was
successful.
Edge Deletion Operation
1. Determine the two vertices connected by the edge to be deleted.
2. Check for the existence of the edge to ensure the connection is present.
3. Remove the edge from the graph’s data structure:
ü Adjacency List: Remove the neighbor entry on both vertices (for
undirected graphs) or in one direction (for directed graphs).
ü Adjacency Matrix: Change the value from 1 or a specific weight to 0 or ∞.
4. Update the graph data to reflect the connection change.
5. Verify the edge deletion to ensure the connection is completely removed.
Pathfinder Operation
1. Determine the start and destination nodes for the path search.
2. Choose the appropriate algorithm based on the graph type: a) BFS for
unweighted graphs; b) Dijkstra for positively weighted graphs; c) A⁎ (A-Star)
for heuristic-based searches; d) Floyd-Warshall for all-pairs shortest paths.
3. Initialize data structures such as initial distances, visited nodes, and
queues or priority queues.
4. Perform iterative pathfinding by updating the shortest distance or
heuristic values until the destination node is reached.
5. Reconstruct the path from the search results to obtain the optimal route.
Traversal of
Graph
1. Breadth-First Search (BFS)
2. Depth-First Search (DFS)
Breadth-First Search
Breadth-First Search is a graph traversal algorithm that visits nodes level by
level, starting from a source node and gradually expanding to all connected
nodes. It uses a queue data structure to store nodes to be visited.
ü Steps: start from the initial node, enqueue it, visit all unvisited neighbors, add
them to the queue, and repeat until all nodes are visited.
ü Advantages: Can find the shortest path in an unweighted graph.
ü Disadvantages: Requires large memory since many nodes must be stored in
the queue during traversal.
Depth-First Search
Depth-First Search is a graph traversal algorithm that explores each branch
deeply before moving to another branch. It is suitable for problems such as
element search, cycle detection, and path exploration in graphs. It uses
recursion or a stack to track visited nodes.
ü Steps: start from the source node, visit unvisited neighboring nodes, perform
deep traversal, and backtrack when no neighbors remain.
ü Advantages: Requires less memory compared to BFS.
ü Disadvantages: Does not guarantee finding the shortest path in a graph.
Algorithm of
Graph
1. Dijkstra's Algorithm
2. Prim's Algorithm
3. Kruskal's Algorithm
4. Bellman-Ford Algorithm
5. Floyd-Warshall Algorithm
Djikstra Algorithm
Dijkstra’s algorithm is used to find the shortest path between two nodes in a
weighted graph without negative weights. It works on the greedy principle,
selecting the node with the shortest distance at each step.
ü Initialization: set the source node distance = 0, and all others = infinity.
ü Iterative process: update neighboring node distances through the nearest
node, then choose the next node with the minimum distance. Stop when all
nodes have been visited.
ü Advantages: efficient and accurate for positive-weight graphs (complexity
O(V²) or O(E + V log V)).
ü Disadvantages: cannot handle negative edge weights.
Prim Algorithm
Prim’s algorithm is used to find the Minimum Spanning Tree (MST) of a
weighted and connected graph — a tree with the smallest total edge weight. It
follows a greedy principle, selecting the smallest weighted edge that connects a
visited node to an unvisited one.
ü Steps: start from a random node, choose the smallest edge connecting to a
new node, add it to the MST, and repeat until all nodes are connected.
ü Advantages: efficient for connected graphs with a complexity of O(E log V)
when using a heap.
ü Disadvantages: cannot be applied to disconnected graphs.
Kruskal Algorithm
Kruskal’s algorithm is used to find the Minimum Spanning Tree (MST) by
globally selecting the smallest weighted edges, unlike Prim’s algorithm which
grows from the nearest node. It follows a greedy approach, adding the smallest
edge to the MST as long as it does not form a cycle.
ü Steps: sort all edges by weight, select the smallest edge that does not create
a cycle, and repeat until all vertices are connected.
ü Advantages: simple, easy to implement, and efficient for sparse graphs.
ü Disadvantages: requires additional data structures such as Union-Find to
detect cycles.
Bellman-Ford Algorithm
Bellman-Ford algorithm is used to find the shortest path in a weighted graph,
including those with negative edge weights. It works on the principle of edge
relaxation — updating a vertex’s distance if a shorter path is found. The
relaxation process is repeated (V−1) times, followed by a check for negative
cycles.
ü Steps: initialize distances (source = 0, others = ∞), relax all edges (V−1
times), then check for negative cycles.
ü Advantages: can handle negative weights and detect negative cycles.
ü Disadvantages: less efficient for large graphs due to its O(V·E) complexity.
Floyd-Warshall Algorithm
Floyd-Warshall algorithm is used to find the shortest paths between all pairs
of vertices in both directed and undirected graphs. Unlike Dijkstra’s algorithm,
which focuses on a single source, this algorithm computes all path
combinations using a dynamic programming approach. Working principle: it
updates the distance between vertices by considering other vertices as
intermediates to find shorter paths.
ü Steps: initialize the distance matrix, iterate through each vertex to update
distances between vertex pairs, until all shortest paths are found.
ü Advantages: computes all shortest paths simultaneously.
ü Disadvantages: high complexity of O(V³), making it less efficient for large
graphs.
Application of Graph
1. Computer Networks: Graphs are used to model network topologies, where
vertices represent devices and edges represent connections. Applications
include routing (OSPF, RIP), analyzing alternative paths during failures, and
optimizing bandwidth.
2. Pathfinding Algorithms: Graphs help find the shortest or optimal paths in
navigation systems (Google Maps, Waze) and game AI using algorithms such
as Dijkstra, A*, and Bellman-Ford.
3. Social Networks: Vertices represent users, and edges indicate relationships
or interactions. Graph theory is applied for influence analysis (centrality),
community detection, and information flow mapping, as seen in Facebook
Graph API and LinkedIn.
Application of Graph
4. Recommendation Systems: Bipartite graphs connect users and products,
enabling methods such as collaborative filtering and graph-based ranking to
deliver personalized recommendations (movies, music, products) on
platforms like Netflix, Spotify, and Amazon.
5. Routing and Logistics Systems: Graphs are used to determine optimal
distribution routes using algorithms like Floyd-Warshall and Minimum
Spanning Tree (Prim/Kruskal). Applications include goods delivery, ride-
hailing services, and autonomous robot navigation.
Department of Informatics
Faculty of Industrial Engineering
Universitas Pembangunan Nasional “Veteran” Yogyakarta
Andi Nurkholis, S.Kom., M.Kom.
November 24, 2025
Done
Thank
You

Data Structure - 12 Graph

  • 1.
    Department of Informatics Facultyof Industrial Engineering Universitas Pembangunan Nasional “Veteran” Yogyakarta Data Structure Andi Nurkholis, S.Kom., M.Kom. Graph: Concept & Implementation November 24, 2025
  • 2.
    Definition of Graph Graphis an important data structure that represents relationships between nodes through edges, either directed or undirected. Graphs are widely used in various fields such as computer networks, transportation, social networks, data analysis, logistics planning, and complex system optimization. More formally, a graph can be defined as an ordered pair (G = (V, E)), where: ü (V) is the set containing the vertices or nodes in the graph. ü (E) is the set containing the edges that connect pairs of vertices.
  • 3.
    Component of Graph 1. Vertex(Node) 2. Edge 3. Degree
  • 4.
    Component of Graph 1.Vertex (Node): The fundamental entity of a graph representing an object or point with a unique identity, such as a city in a transportation network or a user in a social network. 2. Edge: The connection between nodes, which can be directed or undirected, and may carry weights such as distance, cost, or time. 3. Degree: The number of edges connected to a node. In an undirected graph, the degree indicates the number of direct connections of that node. In a directed graph, there are two types of degrees: a) In-degree: The number of edges entering the node; b) Out-degree: The number of edges leaving the node.
  • 5.
    Types of Graph 1. UndirectedGraph) 2. Directed Graph) 3. Weighted Graph 4. Disconnected Graph 5. Connected Graph
  • 6.
    Types of Graph 6. CyclicGraph 7. Acyclic Graph 8. Tree 9. Bipartite Graph
  • 7.
    Types of Graph 1.Undirected Graph: The edges have no direction, meaning the relationship between two vertices is mutual. If vertex A is connected to vertex B, then B is also automatically connected to A. 2. Directed Graph: Each edge has a specific direction indicating a one-way relationship between vertices. If there is an edge from A to B, the connection does not automatically exist from B to A. 3. Weighted Graph: Each edge carries a specific weight or value that can represent distance, time, or cost between vertices. This type of graph is commonly used in communication networks and transportation systems.
  • 8.
    Types of Graph 4.Disconnected Graph: A graph is said to be disconnected if there exists at least one vertex that has no direct connection with other vertices. 5. Connected Graph: A graph is said to be connected if every pair of vertices can be linked by a path. 6. Cyclic Graph: A graph is said to be cyclic if it contains a cycle, meaning a path that starts and ends at the same vertex.
  • 9.
    Types of Graph 7.Acyclic Graph: A graph is said to be acyclic if it contains no cycles. One common example of an acyclic graph is a tree. 8. Tree Graph: A tree is a connected graph with no cycles, consisting of a root node and branch nodes. Trees possess specific properties that simplify computation and structural analysis. 9. Bipartite Graph: A bipartite graph is a graph whose vertices are divided into two distinct sets, where each edge connects a vertex from the first set to one in the second set, with no edges connecting vertices within the same set.
  • 10.
    Representation of Graph Tostore and operate on graphs efficiently, we need a memory-efficient representation method. There are two common approaches used to represent graphs in memory: ü Adjacency Matrix: A two-dimensional square matrix that shows the relationships between vertices in a graph. A value of 1 (or a weight) indicates the presence of an edge, while 0 means no connection. Its advantage is fast access time, but the drawback is high space usage of O(V²) for sparse graphs. Example of an adjacency matrix for a directed graph: A B C D A 0 1 0 0 B 0 0 1 0 C 1 0 0 1 D 0 0 1 0
  • 11.
    Representation of Graph üAdjacency list: Struktur data yang lebih hemat memori daripada adjacency matrix, terutama pada graf yang jarang. Pada adjacency list, setiap simpul memiliki daftar yang berisi simpul-simpul yang terhubung langsung dengannya. Kelebihan: Lebih hemat memori, terutama pada graf yang jarang (sparse graph). Kekurangan: Tidak efisien untuk memeriksa keberadaan sisi antara dua simpul, karena memerlukan pencarian dalam daftar. Contoh adjacency list untuk graf berarah: A -> B B -> C C -> A, D D -> C
  • 12.
    Basic Operation of Graph 1.Vertex Insertion 2. Edge Insertion 3. Vertex Deletion 4. Edge Deletion 5. Pathfinder
  • 13.
    Vertex Insertion Operation 1.Determine the new vertex to be added, including its unique identifier. 2. Check whether the vertex already exists to prevent duplication. 3. Add it to the graph data structure: ü Adjacency List: Create an empty list for the new vertex. ü Adjacency Matrix: Add a new row and column initialized with 0. 4. Update the total number of vertices in the graph. 5. Verify the vertex addition to ensure the new node has been successfully added.
  • 14.
    Edge Insertion Operation 1.Determine the two vertices to be connected by the new edge. 2. Check existence of both vertices to ensure they are present in the graph. 3. Add the edge according to the type of graph: ü Undirected Graph: Add connections in both directions (A→B and B→A). ü Directed Graph: Add a one-way connection (e.g., A→B). 4. If the graph is weighted, also include the weight value (e.g., distance, time). 5. Update the data structure with the new connection. 6. Verify the addition to ensure the new edge has been successfully created.
  • 15.
    Vertex Deletion Operation 1.Determine the vertex to be deleted based on its unique identifier. 2. Check the existence of the vertex to ensure it is present in the graph. 3. Remove all edges connected to that vertex: ü Adjacency List: Remove it from all neighbor lists. ü Adjacency Matrix: Delete the corresponding row and column. 4. Remove the vertex from the graph’s data structure. 5. Update the total number of vertices and verify that the deletion was successful.
  • 16.
    Edge Deletion Operation 1.Determine the two vertices connected by the edge to be deleted. 2. Check for the existence of the edge to ensure the connection is present. 3. Remove the edge from the graph’s data structure: ü Adjacency List: Remove the neighbor entry on both vertices (for undirected graphs) or in one direction (for directed graphs). ü Adjacency Matrix: Change the value from 1 or a specific weight to 0 or ∞. 4. Update the graph data to reflect the connection change. 5. Verify the edge deletion to ensure the connection is completely removed.
  • 17.
    Pathfinder Operation 1. Determinethe start and destination nodes for the path search. 2. Choose the appropriate algorithm based on the graph type: a) BFS for unweighted graphs; b) Dijkstra for positively weighted graphs; c) A⁎ (A-Star) for heuristic-based searches; d) Floyd-Warshall for all-pairs shortest paths. 3. Initialize data structures such as initial distances, visited nodes, and queues or priority queues. 4. Perform iterative pathfinding by updating the shortest distance or heuristic values until the destination node is reached. 5. Reconstruct the path from the search results to obtain the optimal route.
  • 18.
    Traversal of Graph 1. Breadth-FirstSearch (BFS) 2. Depth-First Search (DFS)
  • 19.
    Breadth-First Search Breadth-First Searchis a graph traversal algorithm that visits nodes level by level, starting from a source node and gradually expanding to all connected nodes. It uses a queue data structure to store nodes to be visited. ü Steps: start from the initial node, enqueue it, visit all unvisited neighbors, add them to the queue, and repeat until all nodes are visited. ü Advantages: Can find the shortest path in an unweighted graph. ü Disadvantages: Requires large memory since many nodes must be stored in the queue during traversal.
  • 20.
    Depth-First Search Depth-First Searchis a graph traversal algorithm that explores each branch deeply before moving to another branch. It is suitable for problems such as element search, cycle detection, and path exploration in graphs. It uses recursion or a stack to track visited nodes. ü Steps: start from the source node, visit unvisited neighboring nodes, perform deep traversal, and backtrack when no neighbors remain. ü Advantages: Requires less memory compared to BFS. ü Disadvantages: Does not guarantee finding the shortest path in a graph.
  • 21.
    Algorithm of Graph 1. Dijkstra'sAlgorithm 2. Prim's Algorithm 3. Kruskal's Algorithm 4. Bellman-Ford Algorithm 5. Floyd-Warshall Algorithm
  • 22.
    Djikstra Algorithm Dijkstra’s algorithmis used to find the shortest path between two nodes in a weighted graph without negative weights. It works on the greedy principle, selecting the node with the shortest distance at each step. ü Initialization: set the source node distance = 0, and all others = infinity. ü Iterative process: update neighboring node distances through the nearest node, then choose the next node with the minimum distance. Stop when all nodes have been visited. ü Advantages: efficient and accurate for positive-weight graphs (complexity O(V²) or O(E + V log V)). ü Disadvantages: cannot handle negative edge weights.
  • 23.
    Prim Algorithm Prim’s algorithmis used to find the Minimum Spanning Tree (MST) of a weighted and connected graph — a tree with the smallest total edge weight. It follows a greedy principle, selecting the smallest weighted edge that connects a visited node to an unvisited one. ü Steps: start from a random node, choose the smallest edge connecting to a new node, add it to the MST, and repeat until all nodes are connected. ü Advantages: efficient for connected graphs with a complexity of O(E log V) when using a heap. ü Disadvantages: cannot be applied to disconnected graphs.
  • 24.
    Kruskal Algorithm Kruskal’s algorithmis used to find the Minimum Spanning Tree (MST) by globally selecting the smallest weighted edges, unlike Prim’s algorithm which grows from the nearest node. It follows a greedy approach, adding the smallest edge to the MST as long as it does not form a cycle. ü Steps: sort all edges by weight, select the smallest edge that does not create a cycle, and repeat until all vertices are connected. ü Advantages: simple, easy to implement, and efficient for sparse graphs. ü Disadvantages: requires additional data structures such as Union-Find to detect cycles.
  • 25.
    Bellman-Ford Algorithm Bellman-Ford algorithmis used to find the shortest path in a weighted graph, including those with negative edge weights. It works on the principle of edge relaxation — updating a vertex’s distance if a shorter path is found. The relaxation process is repeated (V−1) times, followed by a check for negative cycles. ü Steps: initialize distances (source = 0, others = ∞), relax all edges (V−1 times), then check for negative cycles. ü Advantages: can handle negative weights and detect negative cycles. ü Disadvantages: less efficient for large graphs due to its O(V·E) complexity.
  • 26.
    Floyd-Warshall Algorithm Floyd-Warshall algorithmis used to find the shortest paths between all pairs of vertices in both directed and undirected graphs. Unlike Dijkstra’s algorithm, which focuses on a single source, this algorithm computes all path combinations using a dynamic programming approach. Working principle: it updates the distance between vertices by considering other vertices as intermediates to find shorter paths. ü Steps: initialize the distance matrix, iterate through each vertex to update distances between vertex pairs, until all shortest paths are found. ü Advantages: computes all shortest paths simultaneously. ü Disadvantages: high complexity of O(V³), making it less efficient for large graphs.
  • 27.
    Application of Graph 1.Computer Networks: Graphs are used to model network topologies, where vertices represent devices and edges represent connections. Applications include routing (OSPF, RIP), analyzing alternative paths during failures, and optimizing bandwidth. 2. Pathfinding Algorithms: Graphs help find the shortest or optimal paths in navigation systems (Google Maps, Waze) and game AI using algorithms such as Dijkstra, A*, and Bellman-Ford. 3. Social Networks: Vertices represent users, and edges indicate relationships or interactions. Graph theory is applied for influence analysis (centrality), community detection, and information flow mapping, as seen in Facebook Graph API and LinkedIn.
  • 28.
    Application of Graph 4.Recommendation Systems: Bipartite graphs connect users and products, enabling methods such as collaborative filtering and graph-based ranking to deliver personalized recommendations (movies, music, products) on platforms like Netflix, Spotify, and Amazon. 5. Routing and Logistics Systems: Graphs are used to determine optimal distribution routes using algorithms like Floyd-Warshall and Minimum Spanning Tree (Prim/Kruskal). Applications include goods delivery, ride- hailing services, and autonomous robot navigation.
  • 29.
    Department of Informatics Facultyof Industrial Engineering Universitas Pembangunan Nasional “Veteran” Yogyakarta Andi Nurkholis, S.Kom., M.Kom. November 24, 2025 Done Thank You