Grokking Algorithms



Download 6,4 Mb.
Pdf ko'rish
bet56/120
Sana21.12.2022
Hajmi6,4 Mb.
#893167
1   ...   52   53   54   55   56   57   58   59   ...   120
Bog'liq
Grokking Algorithms An Illustrated Guide for Programmers and Other

Chapter 6
 
 
I
 
 
Breadth-irst search
If you enqueue two items to the list, th
e irst item you added will be 
dequeued before the second item. You can use this for your search list! 
People who are added to the list irst will be dequeued and searched 
irst.
he queue is called a 
FIFO
data structure: First In, First Out. In 
contrast, a stack is a 
LIFO
data structure: Last In, First Out.
Now that you know how a queue works, let’s implement breadth-irst 
search!
EXERCISES
Run the breadth-irst search algorithm on each of these graphs to ind 
the solution.
6.1
Find the length of the shortest path
from start to inish.
6.2
Find the length of the shortest path
from “cab” to “bat”.


105
Implementing the graph
Implementing the graph
First, you need to implement the graph in code. A graph 
consists of several nodes.
And each node is connected to neighboring nodes. 
How do you express a relationship like “you -> bob”? 
Luckily, you know a data structure that lets you express 
relationships: 
a hash table
!
Remember, a hash table allows you to map a key to a 
value. In this case, you want to map a node to all of its 
neighbors.
Here’s how you’d write it in Python:
graph = {}
graph[“you”] = [“alice”, “bob”, “claire”]
Notice that “you” is mapped to an array. So 
graph[“you”]
will give you 
an array of all the neighbors of “you”.
A graph is just a bunch of nodes and edges, so this is all you need to 
have a graph in Python. What about a bigger graph, like this one?


106

Download 6,4 Mb.

Do'stlaringiz bilan baham:
1   ...   52   53   54   55   56   57   58   59   ...   120




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©hozir.org 2024
ma'muriyatiga murojaat qiling

kiriting | ro'yxatdan o'tish
    Bosh sahifa
юртда тантана
Боғда битган
Бугун юртда
Эшитганлар жилманглар
Эшитмадим деманглар
битган бодомлар
Yangiariq tumani
qitish marakazi
Raqamli texnologiyalar
ilishida muhokamadan
tasdiqqa tavsiya
tavsiya etilgan
iqtisodiyot kafedrasi
steiermarkischen landesregierung
asarlaringizni yuboring
o'zingizning asarlaringizni
Iltimos faqat
faqat o'zingizning
steierm rkischen
landesregierung fachabteilung
rkischen landesregierung
hamshira loyihasi
loyihasi mavsum
faolyatining oqibatlari
asosiy adabiyotlar
fakulteti ahborot
ahborot havfsizligi
havfsizligi kafedrasi
fanidan bo’yicha
fakulteti iqtisodiyot
boshqaruv fakulteti
chiqarishda boshqaruv
ishlab chiqarishda
iqtisodiyot fakultet
multiservis tarmoqlari
fanidan asosiy
Uzbek fanidan
mavzulari potok
asosidagi multiservis
'aliyyil a'ziym
billahil 'aliyyil
illaa billahil
quvvata illaa
falah' deganida
Kompyuter savodxonligi
bo’yicha mustaqil
'alal falah'
Hayya 'alal
'alas soloh
Hayya 'alas
mavsum boyicha


yuklab olish