Grokking Algorithms



Yüklə 348,95 Kb.
Pdf görüntüsü
səhifə58/122
tarix05.12.2023
ölçüsü348,95 Kb.
#173611
1   ...   54   55   56   57   58   59   60   61   ...   122
grokking-algorithms-illustrated-programmers-curious

Chapter 6
 
 
I
 
 
Breadth-first search
Here it is as Python code:
graph = {}
graph[“you”] = [“alice”, “bob”, “claire”]
graph[“bob”] = [“anuj”, “peggy”]
graph[“alice”] = [“peggy”]
graph[“claire”] = [“thom”, “jonny”]
graph[“anuj”] = []
graph[“peggy”] = []
graph[“thom”] = []
graph[“jonny”] = []
Pop quiz: does it matter what order you add the key/value pairs in? 
Does it matter if you write
graph[“claire”] = [“thom”, “jonny”]
graph[“anuj”] = []
instead of
graph[“anuj”] = []
graph[“claire”] = [“thom”, “jonny”]
Think back to the previous chapter. Answer: It doesn’t matter. Hash 
tables have no ordering, so it doesn’t matter what order you add
key/value pairs in.
Anuj, Peggy, Thom, and Jonny don’t have any neighbors. They have 
arrows pointing to them, but no arrows from them to someone else. 
This is called a 
directed graph
—the relationship is only one way. So Anuj 
is Bob’s neighbor, but Bob isn’t Anuj’s neighbor. An undirected graph 
doesn’t have any arrows, and both nodes are each other’s neighbors. For 
example, both of these graphs are equal.


107
Implementing the algorithm
Implementing the algorithm
To recap, here’s how the implementation will work.
Make a queue to start. In Python, you use the double-ended queue 
(
deque
) function for this:
from collections import deque
search_queue = deque() 
search_queue += graph[“you”] 
Remember, 
graph
[
“you”
] will give you a list of all your 
neighbors, like [
“alice”, “bob”, “claire”
]. Those all get 
added to the search queue.
Creates a new queue

Yüklə 348,95 Kb.

Dostları ilə paylaş:
1   ...   54   55   56   57   58   59   60   61   ...   122




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©azkurs.org 2024
rəhbərliyinə müraciət

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin