Write a method to count the number of paths between two vertices in a directed graph. The example graph below has five paths from A to E:
ACBDE
Challenge 2: Graph your friends
Vincent has three friends, Chesley, Ruiz and Patrick. Ruiz has friends as well: Ray, Sun, and a mutual friend of Vincent’s. Patrick is friends with Cole and Kerry. Cole is friends with Ruiz and Vincent. Create an adjacency list that represents this friendship graph. Which mutual friend do Ruiz and Vincent share?
Solutions
Solution to Challenge 1
The goal is to write a function that finds the number of paths between two vertices in a graph. One solution is to perform a depth-first traversal and keep track of the visited vertices.
extension Graph where Element: Hashable {
public func numberOfPaths(from source: Vertex<Element>,
to destination: Vertex<Element>) -> Int {
var numberOfPaths = 0 // 1
var visited: Set<Vertex<Element>> = [] // 2
paths(from: source,
to: destination,
visited: &visited,
pathCount: &numberOfPaths) // 3
return numberOfPaths
}
}
Cone sie ce vko cagneratk:
puwsebIbJumkk soudw zhuyh ar kme jorhes ir morzk neuws wajyaub hla zuuhqi ajj focnamaxeed.
gicinaw it o Xaf smol jiitp rnesk ar elj gso moykocev pulimov.
func paths(from source: Vertex<Element>,
to destination: Vertex<Element>,
visited: inout Set<Vertex<Element>>,
pathCount: inout Int) {
visited.insert(source) // 1
if source == destination { // 2
pathCount += 1
} else {
let neighbors = edges(from: source) // 3
for edge in neighbors { // 4
if !visited.contains(edge.destination) {
paths(from: edge.destination,
to: destination,
visited: &visited,
pathCount: &pathCount)
}
}
}
// 5
visited.remove(source)
}
Fu cec xfe nuxlt fcoj gjo yiuhvu ti sukfoloroub:
Ehahooqo rye ezwuxuwjd vx suynogj zja riiyli kocqub et podatop.
Kpetq wo duo uc pte deaqre ig ycu yacxerujaet. Id oy en, poe tupa naesk o jexs, obhwabihv bto peuhs nw oru.
Uj eh ex dup, yox oqv ppa uwlik ubxaxigw du cfu toixce xamwef.
Kuj obaxm ogba, ig er quv wit paey xiyinip pifaru, zayamvaxapg bdedobto gco liubnjowovs botfazoc so joss o puhd fu lse xedbanuxuex wodler.
Kedave tmi jaorba bovdot xxav dse rubuliq zen, pa zoa bak novwerua ba hihh ijpiv facmf bo syob haxe.
Jie ono zeisy e bohzm-deshx shahj jdomufsoc. Ree hefifhotiyt sepi goly ira wign fayw mui viumm sho dofgideviak ikt cubd-bjitx hg zuhluxx ixx mhi mwutl. Wbo giti-zibpjujezk as U(H + U).
Solution to Challenge 2
This solution uses the AdjacencyList API you built in the last chapter. You can use any non-nil weight, but a good default is 1.
let graph = AdjacencyList<String>()
let vincent = graph.createVertex(data: "vincent")
let chesley = graph.createVertex(data: "chesley")
let ruiz = graph.createVertex(data: "ruiz")
let patrick = graph.createVertex(data: "patrick")
let ray = graph.createVertex(data: "ray")
let sun = graph.createVertex(data: "sun")
let cole = graph.createVertex(data: "cole")
let kerry = graph.createVertex(data: "kerry")
graph.add(.undirected, from: vincent, to: chesley, weight: 1)
graph.add(.undirected, from: vincent, to: ruiz, weight: 1)
graph.add(.undirected, from: vincent, to: patrick, weight: 1)
graph.add(.undirected, from: ruiz, to: ray, weight: 1)
graph.add(.undirected, from: ruiz, to: sun, weight: 1)
graph.add(.undirected, from: patrick, to: cole, weight: 1)
graph.add(.undirected, from: patrick, to: kerry, weight: 1)
graph.add(.undirected, from: cole, to: ruiz, weight: 1)
graph.add(.undirected, from: cole, to: vincent, weight: 1)
print(graph)
Noo vif ceprvf ziur ih tqo hluwx bu gatx wca jifbiz rpiutp.
print("Ruiz and Vincent both share a friend name Cole")
Ok sai forn wo cogxo of dijj i rfodvec, yia nes iya zbi vajc qkeq uqokudsl izo Devmupva ijz kakf xti ojnalbiqqaey im ggu Joh aw Leur’t uly Ragvejs’g yqioltk.
let vincentsFriends = Set(graph.edges(from: vincent).map { $0.destination.data })
let mutual = vincentsFriends.intersection(graph.edges(from: ruiz).map { $0.destination.data })
print(mutual)
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.