Data Structures and Algorithms in Kotlin-3
This part includes:
5.Graphs
I suggest you try to code the examples while you’re reading or after, you can use online kotlin playground https://play.kotlinlang.org/
1.Graphs
A graph is a data structure that captures relationships between objects. It’s made up of vertices connected by edges. In a weighted graph, every edge has a weight associated with it that represents the cost of using this edge. This lets you choose the cheapest or shortest path between two vertices.
Directed Graphs: As well as assigning a weight to an edge, your graphs can also have direction. Directed graphs are more restrictive to traverse, as an edge may only permit traversal in one direction.
Undirected Graphs: You can think of an undirected graph as a directed graph where all of the edges are bi-directional.
This interface describes the common operations for a graph:
createVertex(): Creates a vertex and adds it to the graph.
addDirectedEdge(): Adds a directed edge between two vertices.
addUndirectedEdge(): Adds an undirected (or bi-directional) edge between two vertices.
add(): Uses EdgeType to add either a directed or undirected edge between two vertices.
edges(): Returns a list of outgoing edges from a specific vertex.
weight(): Returns the weight of the edge between two vertices.
Adjacency list
For every vertex in the graph, the graph stores a list of outgoing edges.
Vertices -> Adjacency Lists
Singapore -> Tokyo, Hong Kong
Hong Kong -> Tokyo, Singapore, San Francisco
Tokyo -> Singapore, Hong Kong, Detroit, Washington
Detroit -> Tokyo
Washington -> Tokyo, San Francisco
San Francisco -> Hong Kong, Washington
There’s a lot you can learn from this adjacency list:
- Singapore’s vertex has two outgoing edges. There’s a flight from Singapore to Tokyo and Hong Kong.
- Detroit has the smallest number of outgoing traffic.
- Tokyo is the busiest airport, with the most outgoing flights.
That there are directed and undirected graphs.
Visualizing the adjacency list
Building a network
That’s all for the final part. I hope everything is clear enough to understand. You can find full code and more examples with details in my github.
If you find this helpful, please don’t forget to follow, that motivates me so much to keep writing. 💙
Sources :
1-Data Structures & Algorithms in Kotlin ( Book by Irina Galata and Matei Suica)