Learn

A weighted graph is a graph where the edges are associated with a numeric value.

Weighted graphs are usually directed graphs but it a graph can be both weighted and undirected. If a graph is undirected, the edge is weighted the same for both directions.

One example of a directed graph is a commercial flight map. The nodes are the airports, the edges are the flights from airport to airport, and the weights are the prices of the flights.

Let’s update our GraphEdge and Graph to allow for weights.

Instructions

1.

Inside the GraphEdge structure, add a weight variable that is an optional Int. Set this value to nil.

2.

Next, modify the GraphEdge initializer to allow for an optional weight parameter. Add weight as a third parameter of type optional Int. Give it a default value of nil so that our unweighted code from earlier will still compile.

In the body of the initializer, set the instance weight property equal to the weight parameter value.

3.

Now that a GraphEdge has a weight, add a fourth parameter to addEdge(from:to:isBidirectional:) of type Int? named weight with a default value of nil.

4.

Inside addEdge(from:to:isBidirectional:weight:), modify both initializers for GraphEdge to use the weight passed into the method.

5.

Let’s alter addEdges(from:to:) function to add edges that might have weights. Inside the tuple, add a third value weight of type Int?Since there is a new value in the tuple, add weight to the tuple decomposition.

6.

Finally, update the call to addEdge(from:to:isBidirectional:weight:) to include the weight argument.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?