Building Graph Algorithms with Swift

Here’s the process of establishing an edge: //add edge to source vertex func addEdge(source: Vertex, neighbor: Vertex, weight: Int) { //new edge let newEdge = Edge() //establish default properties newEdge.neighbor = neighbor newEdge.weight = weight source.neighbors.append(newEdge)//check condition for an undirected graph if isDirected == false {//create a new reversed edge let reverseEdge = Edge() //establish the reversed properties reverseEdge.neighbor = source reverseEdge.weight = weight neighbor.neighbors.append(reverseEdge) } }The function addEdge receives two vertices, identifying them as source and neighbor..Since our model defaults to a directed graph, a new Edge is created and is added to the adjacency list of the source Vertex..For an undirected graph, an additional Edge is created and added to the neighbor Vertex.As we’ve seen, there are many components to graph theory..In the next section, we’ll examine a popular problem (and solution) with graphs known as shortest paths.. More details

Leave a Reply