# 1. Introduction

In this tutorial, we will learn how to implement a simple Graph structure using Kotlin programming language.

A Graph is a collection of nodes (vertices) with edges connecting them. These structures are ubiquitous in computer science and can represent various real-world entities like road networks, social networks, and more. In this post, we will discuss a comprehensive Graph implementation in Kotlin and cover common operations such as adding vertices, adding edges, removing vertices, removing edges, and displaying the graph.

# 2. Implementation Steps

1. Define a Graph class.

2. Use a HashMap to store vertices and their respective adjacent vertices.

3. Implement methods for adding and removing vertices and edges.

4. Implement a method to display the graph.

# 3. Implementation in Kotlin Programming

``````class Graph {
private val adjList: HashMap<Int, MutableList<Int>> = HashMap()

// Adds a vertex to the graph
}

// Adds an edge between two vertices
fun addEdge(v1: Int, v2: Int) {
}

// Removes a vertex and its associated edges
fun removeVertex(vertex: Int) {
}
}

// Removes an edge between two vertices
fun removeEdge(v1: Int, v2: Int) {
}

// Displays the graph
fun display() {
for ((vertex, edges) in adjList) {
println("\$vertex -> \$edges")
}
}
}

// client code to test Graph Implementation in Kotlin
fun main() {
val graph = Graph()
graph.display()
graph.removeEdge(2, 4)
graph.removeVertex(3)
graph.display()
}
``````

### Output:

```1 -> [2, 3]
2 -> [1, 4]
3 -> [1, 4]
4 -> [2, 3]
1 -> [2]
2 -> [1]
4 -> []
```

### Explanation:

1. Graph class: Represents the graph using an adjacency list.

2. adjList: A HashMap where each key is a vertex, and its value is a list of adjacent vertices.

5. removeVertex method: Removes a vertex and its associated edges from the graph.

6. removeEdge method: Removes an edge between two vertices.

7. display method: Prints out the graph in the form of an adjacency list.

8. The main function demonstrates adding vertices and edges, displaying the graph, and then removing vertices and edges followed by another display to see the changes.