Professional Documents
Culture Documents
Veriyapıları Ders Not PDF
Veriyapıları Ders Not PDF
1
Yükseklik Dengeli Ağaçlar
• BST operasyonlarını daha kısa sürede
gerçekleştirmek için pek çok BST dengeleme
algoritması vardır.
– Adelson-Velskii ve Landis (AVL) ağaçları (1962)
– Splay ağaçları (1978)
– B-ağacı ve diğer çok yönlü arama ağaçları (1972)
– Red-Black ağaçları (1972)
• Ayrıca Simetrik İkili B-Ağaçları(Symmetric Binary B-Trees)
şeklinde de bilinir
2
AVL Ağaçları: Tanım
1. Tüm boş ağaç AVL ağacıdır.
2. Eğer T boş olmayan TL ve TR şeklinde sol ve
sağ alt ağaçları olan ikili arama ağacı ise, T
ancak ve ancak aşağıdaki şartları sağlarsa AVL
ağacı şeklinde isimlendirilir.
1. TL ve TR AVL ağaçları ise
2. hL ve hR TL ve TR nin yükseklikleri olmak üzere
|hL – hR| <= 1 olmak zorundadır.
hL+1 or hL-1
hL
TL TR 3
AVL Ağaçları
• AVL ağaçları dengeli ikili arama
ağaçlarıdır. AVL Ağacı
yükseklik(sol altağaç) -
yükseklik(sağ altağaç) 1
4 7
-1
0
• AVL ağaçlarında balans faktörü 1 9 0
4
AVL Ağaçları: Örnekler
6 0 6 -1 6 0
1 4 10 2 0
1 5 7 -1 4 9 1
0 4 0 1 8 0 0 1 5 8 0
9 0
0 7 9 0
AVL Ağacı AVL Ağacı
AVL Ağacı Değildir
6 -1 6 0
6 1
1 2 4 7 -2
4 9 2 0 4 9 0
0 1 7 -1 1 3 8 -1
0 1 5 0
8 0 0 1 9 0
Yükseklik = O(logN)
• Peki nasıl? 6
0
1 -1
5 7
0 4 0
9
7
AVL Ağaçları: Güzel ve Çirkin
• Güzel:
– Arama süresi O(h) = O(logN)
• Çirkin
• Ekleme ve silme işlemleri ağacın dengesiz olmasına neden
olabilir.
0 Ekle 3
6 6 1
1 -1 -1
5 7 2 5 7
0 4 0 1 4
9 9 0
0 3
AVL Tree
Artık AVL ağacı değil
8
AVL Ağacında Dengenin Sağlanması
• Problem: Ekleme işlemi bazı durumlarda ekleme
noktasına göre kök olan bölgelerde balans faktörün 2
veya -2 olmasına neden olabilir.
6 1
2 -1
5 7
1 4 9 0
0 3
9
Denge Sağlama: Örnek
Ekle 3 Döndürme
0
6 6 1 6 0
1 -1 2 -1 -1
5 7 5 7 0 4 7
0 4 9 0 1 4 9 0 0 3 5 0 9 0
AVL 0 3
AVL
AVL Değil
10
AVL Ağacı - Ekleme (1)
P Pivot: bf 2 veya -2
P
L R
A B C D
P P Pivot: bf 2 veya -2
L R
A B C D
1 Ekle(2) 1 1 Döndür
10 10 10 1
10
1 4 20 0 1 4 20 0 2 4 0 20 0 0 3 20 0
0 3 0 3 1 3 0 2 4 0
Başlangıçtaki
0 2 0 2 LL Düzeltmesi
AVL Ağacı Pivotun yapıldıktan sonra
2 eklendikten sonra belirlenmesi AVL ağacı
ağacın durumu
Dengesizliğin türünün
Balans faktörü
belirlenmesi
düzelterek köke
doğru ilerle • LL Dengesizliği:
– P(4)’ün bfsi 2
– L(3)’ün bfsi 0 veya 1 14
LL Dengesizliği Düzeltme Örneği (2)
1 Ekle(2) 2 10 Döndür
10 1 10 0 4
0 4 0 4 1 4 20 0
20 0 20 0
1 3 10 0
0 3 5 0 0 3 1 3 5 0
5 0 0 2 5 0 20 0
Başlangıçtaki 0 2
AVL Ağacı 0 2
Pivotun LL Düzeltmesi
2 eklendikten sonra belirlenmesi yapıldıktan sonra
ağacın durumu AVL ağacı
Dengesizliğin
Balans faktörü türünün
düzelterek köke belirlenmesi
doğru ilerle
• LL Dengesizliği:
– P(4)’ün bfsi 2
– L(3)’ün bfsi 0 veya 1
15
RR Dengesizliği & Düzeltme
Döndür R
P -2
P
L R 0 veya -1 D
L
C
A B C D
Ekledikten sonra A B
Ekle(40) Döndür
10 -1 10 -1 10 -1 10 -1
0 4 20 -1 0 4 20
-1 0 4 20 -2 0 4 30 0
30 0 30 0 30 -1 0 20 40 0
Başlangıçtaki
AVL Ağacı 40 0 40 0 RR Düzeltmesi
yapıldıktan sonra
40 eklendikten sonra Pivotun AVL ağacı
ağacın durumu belirlenmesi
10 -1 Ekle(40) 10 -2 Döndür 20 0
0 4 20 0 0 4 20 -1 0 10 30 -1
0 15 30 0 0 15 30 -1 0 4 15 0 40 0
Başlangıçtaki
40 0
AVL Ağacı
40 eklendikten sonra RR Düzeltmesi
ağacın durumu yapıldıktan sonra
AVL ağacı
Balans faktörü Dengesizliğin türünün
düzelterek köke doğru belirlenmesi
ilerle ve 10’u pivot
olarak belirle • RR Dengesizliği:
– P(10) bf = -2
– R(20) bf = 0 veya -1
LR Dengesizliği & Düzeltme
1. Döndürme 2. Döndürme
2 P P LR
-1 L 2 R LR 2 R L P
1 L
LR R
A C D B2 C D A
B1 B2
A
B1 B2 B1
C D
Eklemeden sonra ağaç 1. Döndürmeden sonra ağaç LR Düzeltmesinden sonra
2
0 4 20 0 -1 4 20 0 0 4 10 -1
1
0 3 7 0 0 3 0 3 5 0 20 0
7 1
R L
1
RL
C1 C1 C2 D
A B D A B
A B
C1 C2 C2 D
Eklemeden sonra ağaç 1. Döndürmeden sonra RL Düzeltmesinden sonra
-1 10 Ekle(17) -2 10 Döndür 15 0
2
0 4 20 1 1 10 20 1
0 4 20 0
1
0 15 30 0 -1 15 30 0 0 4 0 17 30 0
Başlangıçtaki 17 0
RL Düzeltmesi
AVL Ağacı
17 eklendikten sonra yapıldıktan sonra
ağacın durumu AVL ağacı
Balans faktörü
düzelterek köke Dengesizliğin türünün
doğru ilerle ve 10’u belirlenmesi
pivot olarak belirle
• RL Dengesizliği:
– P(10) bf = -2
– R(20) bf = 1 22
Silme
• Silme işlemi ekleme işlemi ile benzerlik
gösterir.
Sil(20)
1 Döndür
10 1
10 2 10 4 -1
0 4 20 0 0 4 0 4 10 1
0 3
0 3 5 0 0 3 5 0 0 3 5 0 0 5
Dengesizliğin
Balans faktörü türünün
düzelterek köke belirlenmesi
doğru ilerle
• LL Dengesizliği:
– P(10)’ün bfsi 2
– L(4)’ün bfsi 0 veya 1
Silme Örneği (2)
Sil(20)
1 Döndür
10 1
10 2 10 5 0
-1 4 20 0 -1 4 -1 4
2
10 0
0 4
1
5 0 LR Düzeltmesinden
5 0 5 0
sonra AVL Ağacı
Başlangıçtaki 20 silindikten sonra 10’un pivot olarak
AVL Ağacı Ağacın durumu belirlenmesi
Balans faktörü
düzelterek köke
doğru ilerle 26
Silme örneği (3) - devam
1
15 Döndür 1
15
-2 1 5 30 0
1 5 20
1 3 -1 7 30 -1 1 3 -1 7 20 0 40 0
1 2 1 2 0 4 0 8
0 4 0 8 0 40
0 1 0 1
20’nin pivot olarak seçilmesi RR Dengesizliği
düzeltildikten sonra
Dengesizliğin
türünü belirle Yukardaki AVL
ağacı mıdır?
• RR Dengesizliği:
Balans faktörü
– P(20) bf = -2 düzelterek köke
– R(30) bf = 0 veya -1 doğru ilerle.
27
Silme Örneği (3) - devam
2 15 Döndür 0 5
1 5 30 0 1 3 15 0
1 3 -1 7 20 0 40 0 1 2 0 4 7 -1 30 0
1 2 0 4 0 8 0 1
0 8 20 0 40 0
Dengesizliğin
türünü belirle
• LL Dengesizliği:
– P(15) bf = 2
– L(5) bf = 0 veya 1 28
Arama (Bul)
• AVL ağacı bir tür İkili Arama Ağacı (BST)
olduğundan arama algoritması BST ile aynıdır.
• O(logN) de çalışması garantidir.
29
AVL Ağaçları - Özet
• AVL Ağaçlarının Avantajları
1. AVL ağacı devamlı dengeli olduğu için
Arama/Ekleme/Silme işlemi O(logN) yapılır.
2. Düzeltme işlemi algoritmaların karmaşıklığını
etkilemez.
• Sezgiseldir.
– Eğer X bir kez erişildi ise, bir kez daha erişilecektir.
– X erişildikten sonra "splaying" operasyonu yapılır.
• X köke taşınır.
1
Örnek
Kök Kök
2
6 18 Splay ana düşünce: 6 15
Döndürme kullanarak
1
3 12 12’yi köke getir. 3 9 14 18
9 14
12 arandıktan sonra
Başlangıçtaki ağaç
• Burada ağacın dengeli olmasının yanı sıra 12 ye O(1)
zamanında erişilebiliyor.
• Aktif (son erişilenler) düğümler köke doğru taşınırken
aktif olmayan düğümler kökten uzaklaştırılır.
2
Splay Ağacı Terminolojisi
• X kök olmayan bir düğüm olsun. (ailesi olan)
• P düğümü X’in aile düğümü olsun.
• G düğümü X’in ata düğümü olsun.
• G ve X arasındaki yol düşünüldüğünde:
– Her sola gitme işlemine “zig” işlemi denilmektedir.
– Her sağa gitme işlemine “zag” işlemi denilmektedir.
• Toplam 6 farklı durum oluşabilir:
G G G G
P P P P P P
X X X X X X
1. zig 2. zig-zig 3. zig-zag 4. zag-zig 5. zag-zag 6. zag
3
Splay Ağaç İşlemleri
• X’e erişildiğinde 6 tane rotasyon işleminden
birisi uygulanır:
– Tek Dönme (X P’ye sahip ama G’ye sahip değil)
• zig, zag
4
Splay Ağaçları: Zig İşlemi
• “Zig” işlemi AVL ağacındaki gibi tek döndürme
işlemidir.
• Örneğin erişilen elemanın 6 olduğu düşünülürse.
15
6
Zig-Sağ
6 18 15
3
3 12 12 18
5
Splay Ağaçları: Zig-Zig İşlemi
• “Zig-Zig” işlemi aynı türde 2 tane dönme işlemi içerir.
• Örneğin erişilen elemanın 3 olduğu düşünülürse.
15 3
Zig-Sağ 6
Zig-Sağ
18 1 6
6 3 15
4 15
3 12 1 4 12 18
1 4 12 18
15 Zag-Sol 15 Zig-Sağ 12
6 18 12 18 6 15
3 10 14 18
3 12 6 14
10 14 3 10
15 15 Zag-Sol 17
Zig-Sağ
6 20 6 15 20
17
6 16 18 30
17 30 16 20
18 30
16 18
15 Zag-Sol 20 Zag-Sol 30
15 30
6 20 20 40
6 17 25 40 15 25
17 30
6 17
25 40
6 15
Zag-Sol
3 15 6 18
12 18 3 12
10
Splay Ağacı Örnek: 40’a Erişildiğinde
80
80 40
70 85
70 85 30 70
60 75 80
50
40 75
50 65 45 60 75 85
30 50
55 65
40 55 45 60
55 65
30 45 Zig-zig
Zig-zig
(a) (b) (c)
11
Splay Ağacı Örnek: 60’a Erişildiğinde
40 40
60
30 70 30 60 40 70
50 70
50 80 30 50 65 80
45 60 75 85 45 55 65 80
45 55 75 85
55 65 75 85
Zig-zag
zag
(a) (b) (c)
12
Diğer işlemler Sırasında Splaying
• Splaying sadece Arama işleminden sonra değil
Ekle/Sil gibi değer işlemlerden sonra da uygulanabilir.
• Sil X: X’i ara ve köke taşı. Kökte bulunan X’i sil ve sol
alt ağaçtaki en büyük elemanı köke taşı.
13
Splay Ağaçları - Özet
• Splaying işlemi ile ağaç genel olarak dengede kalıyor.
14
Örnek - 1
• 1, 2, …, 6 elemanları sırası ile boş bir Splay
ağacına ekleniyor.
• Oluşan ağacı çizerek gösteriniz.
• “6" ya erişim nasıl olur.
• "1" e erişim sağlandıktan sonra ağacın yapısını
çizerek gösteriniz.
15
Örnek - 2
• 1, 2, …, 6 elemanları sırası ile boş bir AVL
ağacına ekleniyor.
• Her bir eleman eklendiğinde oluşan ağaçları
çizerek gösteriniz.
• “6" ya erişim nasıl olur.
16
BAZI PROGRAMLAMA
DİLLERİNDEKİ DOĞRUDAN
KULLANILABİLECEK VERİ
YAPILARI
DERS 11
21.12.2022
İncelenen Diller
• Ruby
• Java
• Python
Ruby Programlama Dili Veri Yapıları
• Yığın
• Kuyruk
• Bağlı Liste
• Hash
Ruby Programlama Dili Veri Yapıları
• Bir dizi, bazı fonksiyonlar ile bir yığın veya kuyruk veri yapısı şeklinde
kullanılabilmektedir. (push, pop, shift, unshift)
-push / pop FILO
-unshift / pop FIFO
• Bağlı listeler
-Sınıf kullanarak bağlantılı bir liste uygulanabilir
-Standart dizi yöntemlerini kullanarak bağlantılı liste benzeri
davranışlar verecektir.
• Maps
-Hash {}
Ruby Programlama Dili Veri Yapıları Örnekler
• Yığın (push / pop)
Ruby Programlama Dili Veri Yapıları Örnekler
• Kuyruk (unshift / pop)
Java Programlama Dili Veri Yapıları
• Set
• List
• Kuyruk
• Dinamik Diziler
• Vector
• ArrayList
Java Collection
• Collection arabirimi, içerisinde koleksiyon elemanları olarak bilinen bir
grup nesne barındırır. Veriyi saklamak, geri almak, güncellemek ve bir
yöntemden diğerine veri aktarmak amaçlarıyla kullanılır.
Java Collection
• Set: Tekrarlı ya da kopya elemanları içerisinde barındırmayan bir
koleksiyondur.
2 3 5
Genişlik Öncelikli Arama (Breadth First
Search)
• Önce 1 numaralı düğüm ziyaret edilir. Kuyruğa alınır (Adım 2),
kuyruktan çıkartılır (Adım 4) ve 1’in tüm komşuları sıra ile ziyaret
edilir ve kuyruğa alınır (Adım 5-8).
1 4
6
2 3 5
• Kuyruk: 2, 3, 4
Genişlik Öncelikli Arama (Breadth First
Search)
• İlk komşu olarak 2 numaralı düğüm ziyaret edilir. Kuyruktan çıkartılır
(Adım 4) ve 2’in tüm komşuları sıra ile ziyaret edilir ve kuyruğa alınır
(Adım 5-8).
1 4
6
2 3 5
• Kuyruk: 3, 4
Genişlik Öncelikli Arama (Breadth First
Search)
• 3 numaralı düğüm ziyaret edilir. Kuyruktan çıkartılır (Adım 4) ve 3’ün
tüm komşuları sıra ile kuyruğa alınır (Adım 5-8).
1 4
6
2 3 5
• Kuyruk: 4,5,6
Genişlik Öncelikli Arama (Breadth First
Search)
• 4 numaralı düğüm ziyaret edilir. Kuyruktan çıkartılır (Adım 4) ve 4’ün tüm
komşuları sıra ile ziyaret edilir ve kuyruğa alınır (Adım 5-8). 6 numaralı
düğüm daha önce kuyruğa alındığı için tekrar alınmaz.
1 4
6
2 3 5
• Kuyruk: 5,6
Genişlik Öncelikli Arama (Breadth First
Search)
• Son iki aşamada 5 ve 6 numaralı düğümler kuyruk dışına alınır.
1 4
6
2 3 5
• Kuyruk: 6
Genişlik Öncelikli Arama (Breadth First
Search)
• Son iki aşamada 5 ve 6 numaralı düğümler kuyruk dışına alınır.
1 4
6
2 3 5
• Kuyruk: Boş
Genişlik öncelikli arama algoritması çalışma
zamanı analizi
• Sözde kodda görüleceği üzere algoritmada her düğüm bir kez kuyruk
içine alınıp işlenmektedir.
• Bu O(V) zamanda tamamlanır. İşlenen her düğümün tüm kenarları
(u, v) için işlem yapılacağı için O(E) zaman gerekir.
• Bu nedenle genişlik öncelikli arama algoritmasının toplam çalışma
zamanı O(V+E) olarak belirlenir.
Derinlik Öncelikli Arama (Depth First Search)
• Verilen bir s düğümünden çizge içindeki ulaşılabilecek diğer tüm
düğümlerin bulunması hedeflenmektedir.
• Ancak genişlik öncelikli aramadan farklı olarak tüm komşuların
öncelikle bulunması yerine bir komşudan ulaşılabilecek diğer tüm
düğümlerin bulunmasına öncelik verilir.
• Bir s düğümüne gidildikten sonra s düğümünün bir komşusu seçilir ve
ziyaret edilir.
• Ardından onun bir komşusu seçilir ve peş peşe komşu seçimi yapılarak
devam edilir.
• Komşu kalmadığında geri dönülür.
Derinlik Öncelikli Arama (Depth First Search)
DOA (G,s)
for each vertex u
visited[u] = false;
push.stack(s);
while (stack is not empty) do
u=pop.stack();
if (visited[u]=false) then
visited[u] = true;
for each unvisited neighbor v of u
push.stack(v)
Derinlik Öncelikli Arama (Depth First Search)
• Sözde koddan anlaşılacağı üzere derinlik öncelikli arama
algoritmasında yığın yapısından faydalanılır.
• Öncelikle tüm düğümlerin ziyaret edilme değişkeni negatif yapılır ve
başlangıç düğümü yığına eklenir.
• Yığın içinden sürekli ilk eleman alınarak ziyaret edilir. Ziyaret sırasında
bu düğümün tüm komşuları da yığına eklenir.
• Kuyruk yapısının aksine yığın yapısında sürekli üstten ekleme ve
çıkarma yapıldığından, derinlemesine bir ilerleme sağlanmış olur.
Derinlik Öncelikli Arama (Depth First Search)
• D düğümden başlayarak derinlik öncelikli arama işlemini uygulayınız.
F
A
A
B
C
C
D x
B E
H
D F
G
H D
G
E Ziyaret
Yığın
edilen
Derinlik Öncelikli Arama (Depth First Search)
• D düğümünün komşuları yığına eklenir ve en üstteki seçilerek devam
edilir (yığına ekleme sırasında alfabetik sıra takip edilecektir).
F
A
A
B
C
C
D x
B E
H
D F
G
H D
G
E Ziyaret
Yığın
edilen
Derinlik Öncelikli Arama (Depth First Search)
• C düğümünün komşusu olmadığı için (yönlendirilmiş çizge olduğuna
dikkat ediniz) yığındaki en üstteki eleman ile devam edilecektir.
F
A
A
B
C
C x
D x
B E
H
D F C
G E
H F
G
E Ziyaret
Yığın
edilen
Derinlik Öncelikli Arama (Depth First Search)
• C düğümünün komşusu olmadığı için (yönlendirilmiş çizge olduğuna
dikkat ediniz) yığındaki en üstteki eleman ile devam edilecektir.
F
A
A
B
C
C x
D x
B E X
H
D F
G E
H F
G
E Ziyaret
Yığın
edilen
Derinlik Öncelikli Arama (Depth First Search)
• E düğümünün komşuları yığına eklenir ve en üstteki seçilerek devam
edilir
F
A
A
B
C
C x
D x
B E X
H
D F
G G
H F
G
E Ziyaret
Yığın
edilen
Derinlik Öncelikli Arama (Depth First Search)
• G düğümünün komşuları yığına eklenir (D ziyaret edildiği için
eklenmez) ve en üstteki seçilerek devam edilir.
F
A
A
B
C
C x
D x
B E X
H
D F
G X H
H F
G
E Ziyaret
Yığın
edilen
Derinlik Öncelikli Arama (Depth First Search)
• H düğümünün komşuları yığına eklenir ve en üstteki seçilerek devam
edilir.
F
A
A
B
C
C x
D x
B E X
H
D F A
G X B
H X F
G
E Ziyaret
Yığın
edilen
Derinlik Öncelikli Arama (Depth First Search)
• A düğümünün komşusu olmadığı için (yönlendirilmiş çizge olduğuna
dikkat ediniz) yığındaki en üstteki eleman ile devam edilecektir.
F
A X
A
B X
C
C x
D x
B E X
H
D F
G X B
H X F
G
E Ziyaret
Yığın
edilen
Derinlik Öncelikli Arama (Depth First Search)
• B düğümünün komşusu olmadığı için (yönlendirilmiş çizge olduğuna
dikkat ediniz) yığındaki en üstteki eleman ile devam edilecektir.
F
A X
A
B X
C
C x
D x
B E X
H
D F
G X
H X F
G
E Ziyaret
Yığın
edilen
Derinlik Öncelikli Arama (Depth First Search)
• F düğümü de ziyaret edildikten sonra yığın boş kalacağı için algoritma
sonlanacaktır.
F
A X
A
B X
C
C x
D x
B E X
H
D F X
G X
H X
G
E Ziyaret
Yığın
edilen
Derinlik öncelikli arama algoritması çalışma
zamanı analizi:
• Derinlik öncelikli arama algoritması genişlik öncelikli arama
algoritması ile benzerlik gösterir.
• Algoritmada her düğüm bir kez ziyaret edilecektir. Bu O(V) zamanda
tamamlanır.
• İşlenen her düğümün tüm kenarı (u, v) için işlem yapılacağı için O(E)
zaman gerekir.
• Bu nedenle derinlik öncelikli arama algoritmasının toplam çalışma
zamanı O(V+E) olarak belirlenir.
DFS – BFS Karşılaştırması
• Hangisi seçilmeli?
• Çalışma zamanları eşit.
• Çözümün ağaçtaki yerine göre değişir
• Aile soy ağacı uygulaması?
• Yaşayan bir aile yakınını arıyorsanız
• Yapraklara yakın bir yerdedir
• DFS daha hızlı çözüme ulaşır
• Çok uzun zaman önce ölmüş birisini arıyorsanız
• Köke yakındır
• BFS daha hızlı çözüme ulaşır
• Sosyal medya arkadaş öneri uygulaması yazacaksınız
• BFS
22.2 Breadth-first search 595
The breadth-first-search procedure BFS below assumes that the input graph
G D .V; E/ is represented using adjacency lists. It attaches several additional
attributes to each vertex in the graph. We store the color of each vertex u 2 V
in the attribute u:color and the predecessor of u in the attribute u:. If u has no
predecessor (for example, if u D s or u has not been discovered), then u: D NIL .
The attribute u:d holds the distance from the source s to vertex u computed by the
algorithm. The algorithm also uses a first-in, first-out queue Q (see Section 10.1)
to manage the set of gray vertices.
BFS.G; s/
1 for each vertex u 2 G:V fsg
2 u:color D WHITE
3 u:d D 1
4 u: D NIL
5 s:color D GRAY
6 s:d D 0
7 s: D NIL
8 QD;
9 E NQUEUE .Q; s/
10 while Q ¤ ;
11 u D D EQUEUE .Q/
12 for each 2 G:AdjŒu
13 if :color == WHITE
14 :color D GRAY
15 :d D u:d C 1
16 : D u
17 E NQUEUE .Q; /
18 u:color D BLACK
r s t u r s t u
∞ 0 ∞ ∞ 1 0 ∞ ∞
(a) Q s (b) Q w r
∞ ∞ ∞ ∞ 0 ∞ 1 ∞ ∞ 1 1
v w x y v w x y
r s t u r s t u
1 0 2 ∞ 1 0 2 ∞
(c) Q r t x (d) Q t x v
∞ 1 2 ∞ 1 2 2 2 1 2 ∞ 2 2 2
v w x y v w x y
r s t u r s t u
1 0 2 3 1 0 2 3
(e) Q x v u (f) Q v u y
2 1 2 ∞ 2 2 3 2 1 2 3 2 3 3
v w x y v w x y
r s t u r s t u
1 0 2 3 1 0 2 3
(g) Q u y (h) Q y
2 1 2 3 3 3 2 1 2 3 3
v w x y v w x y
r s t u
1 0 2 3
(i) Q ;
2 1 2 3
v w x y
Figure 22.3 The operation of BFS on an undirected graph. Tree edges are shown shaded as they
are produced by BFS. The value of u: d appears within each vertex u. The queue Q is shown at the
beginning of each iteration of the while loop of lines 10–18. Vertex distances appear below vertices
in the queue.
Although we won’t use this loop invariant to prove correctness, it is easy to see
that it holds prior to the first iteration and that each iteration of the loop maintains
the invariant. Prior to the first iteration, the only gray vertex, and the only vertex
in Q, is the source vertex s. Line 11 determines the gray vertex u at the head of
the queue Q and removes it from Q. The for loop of lines 12–17 considers each
vertex in the adjacency list of u. If is white, then it has not yet been discovered,
and the procedure discovers it by executing lines 14–17. The procedure paints
vertex gray, sets its distance :d to u:dC1, records u as its parent :, and places
it at the tail of the queue Q. Once the procedure has examined all the vertices on u’s
22.2 Breadth-first search 597
adjacency list, it blackens u in line 18. The loop invariant is maintained because
whenever a vertex is painted gray (in line 14) it is also enqueued (in line 17), and
whenever a vertex is dequeued (in line 11) it is also painted black (in line 18).
The results of breadth-first search may depend upon the order in which the neigh-
bors of a given vertex are visited in line 12: the breadth-first tree may vary, but the
distances d computed by the algorithm will not. (See Exercise 22.2-5.)
Analysis
Before proving the various properties of breadth-first search, we take on the some-
what easier job of analyzing its running time on an input graph G D .V; E/. We
use aggregate analysis, as we saw in Section 17.1. After initialization, breadth-first
search never whitens a vertex, and thus the test in line 13 ensures that each vertex
is enqueued at most once, and hence dequeued at most once. The operations of
enqueuing and dequeuing take O.1/ time, and so the total time devoted to queue
operations is O.V /. Because the procedure scans the adjacency list of each vertex
only when the vertex is dequeued, it scans each adjacency list at most once. Since
the sum of the lengths of all the adjacency lists is ‚.E/, the total time spent in
scanning adjacency lists is O.E/. The overhead for initialization is O.V /, and
thus the total running time of the BFS procedure is O.V C E/. Thus, breadth-first
search runs in time linear in the size of the adjacency-list representation of G.
Shortest paths
At the beginning of this section, we claimed that breadth-first search finds the dis-
tance to each reachable vertex in a graph G D .V; E/ from a given source vertex
s 2 V . Define the shortest-path distance ı.s; / from s to as the minimum num-
ber of edges in any path from vertex s to vertex ; if there is no path from s to ,
then ı.s; / D 1. We call a path of length ı.s; / from s to a shortest path2
from s to . Before showing that breadth-first search correctly computes shortest-
path distances, we investigate an important property of shortest-path distances.
2 In Chapters 24 and 25, we shall generalize our study of shortest paths to weighted graphs, in which
every edge has a real-valued weight and the weight of a path is the sum of the weights of its con-
stituent edges. The graphs considered in the present chapter are unweighted or, equivalently, all
edges have unit weight.
22.3 Depth-first search 603
The strategy followed by depth-first search is, as its name implies, to search
“deeper” in the graph whenever possible. Depth-first search explores edges out
of the most recently discovered vertex that still has unexplored edges leaving it.
Once all of ’s edges have been explored, the search “backtracks” to explore edges
leaving the vertex from which was discovered. This process continues until we
have discovered all the vertices that are reachable from the original source vertex.
If any undiscovered vertices remain, then depth-first search selects one of them as
a new source, and it repeats the search from that source. The algorithm repeats this
entire process until it has discovered every vertex.3
As in breadth-first search, whenever depth-first search discovers a vertex dur-
ing a scan of the adjacency list of an already discovered vertex u, it records this
event by setting ’s predecessor attribute : to u. Unlike breadth-first search,
whose predecessor subgraph forms a tree, the predecessor subgraph produced by
a depth-first search may be composed of several trees, because the search may
repeat from multiple sources. Therefore, we define the predecessor subgraph of
a depth-first search slightly differently from that of a breadth-first search: we let
G D .V; E /, where
E D f.:; / W 2 V and : ¤ NIL g :
The predecessor subgraph of a depth-first search forms a depth-first forest com-
prising several depth-first trees. The edges in E are tree edges.
As in breadth-first search, depth-first search colors vertices during the search to
indicate their state. Each vertex is initially white, is grayed when it is discovered
in the search, and is blackened when it is finished, that is, when its adjacency list
has been examined completely. This technique guarantees that each vertex ends up
in exactly one depth-first tree, so that these trees are disjoint.
Besides creating a depth-first forest, depth-first search also timestamps each ver-
tex. Each vertex has two timestamps: the first timestamp :d records when
is first discovered (and grayed), and the second timestamp :f records when the
search finishes examining ’s adjacency list (and blackens ). These timestamps
3 Itmay seem arbitrary that breadth-first search is limited to only one source whereas depth-first
search may search from multiple sources. Although conceptually, breadth-first search could proceed
from multiple sources and depth-first search could be limited to one source, our approach reflects how
the results of these searches are typically used. Breadth-first search usually serves to find shortest-
path distances (and the associated predecessor subgraph) from a given source. Depth-first search is
often a subroutine in another algorithm, as we shall see later in this chapter.
604 Chapter 22 Elementary Graph Algorithms
provide important information about the structure of the graph and are generally
helpful in reasoning about the behavior of depth-first search.
The procedure DFS below records when it discovers vertex u in the attribute u:d
and when it finishes vertex u in the attribute u:f . These timestamps are integers
between 1 and 2 jV j, since there is one discovery event and one finishing event for
each of the jV j vertices. For every vertex u,
u:d < u:f : (22.2)
Vertex u is WHITE before time u:d, GRAY between time u:d and time u:f , and
BLACK thereafter.
The following pseudocode is the basic depth-first-search algorithm. The input
graph G may be undirected or directed. The variable time is a global variable that
we use for timestamping.
DFS.G/
1 for each vertex u 2 G:V
2 u:color D WHITE
3 u: D NIL
4 time D 0
5 for each vertex u 2 G:V
6 if u:color == WHITE
7 DFS-V ISIT .G; u/
Figure 22.4 illustrates the progress of DFS on the graph shown in Figure 22.2.
Procedure DFS works as follows. Lines 1–3 paint all vertices white and ini-
tialize their attributes to NIL. Line 4 resets the global time counter. Lines 5–7
check each vertex in V in turn and, when a white vertex is found, visit it using
DFS-V ISIT. Every time DFS-V ISIT .G; u/ is called in line 7, vertex u becomes
22.3 Depth-first search 605
u v w u v w u v w u v w
1/ 1/ 2/ 1/ 2/ 1/ 2/
3/ 4/ 3/
x y z x y z x y z x y z
(a) (b) (c) (d)
u v w u v w u v w u v w
1/ 2/ 1/ 2/ 1/ 2/ 1/ 2/7
B B B B
u v w u v w u v w u v w
1/ 2/7 1/8 2/7 1/8 2/7 9/ 1/8 2/7 9/
F B F B F B F B C
u v w u v w u v w u v w
1/8 2/7 9/ 1/8 2/7 9/ 1/8 2/7 9/ 1/8 2/7 9/12
F B C F B C F B C F B C
B B B
4/5 3/6 10/ 4/5 3/6 10/ 4/5 3/6 10/11 4/5 3/6 10/11
x y z x y z x y z x y z
(m) (n) (o) (p)
Figure 22.4 The progress of the depth-first-search algorithm DFS on a directed graph. As edges
are explored by the algorithm, they are shown as either shaded (if they are tree edges) or dashed
(otherwise). Nontree edges are labeled B, C, or F according to whether they are back, cross, or
forward edges. Timestamps within vertices indicate discovery time/finishing times.
the root of a new tree in the depth-first forest. When DFS returns, every vertex u
has been assigned a discovery time u:d and a finishing time u:f .
In each call DFS-V ISIT .G; u/, vertex u is initially white. Line 1 increments
the global variable time, line 2 records the new value of time as the discovery
time u:d, and line 3 paints u gray. Lines 4–7 examine each vertex adjacent to u
and recursively visit if it is white. As each vertex 2 AdjŒu is considered in
line 4, we say that edge .u; / is explored by the depth-first search. Finally, after
every edge leaving u has been explored, lines 8–10 paint u black, increment time,
and record the finishing time in u:f .
Note that the results of depth-first search may depend upon the order in which
line 5 of DFS examines the vertices and upon the order in which line 4 of DFS-
V ISIT visits the neighbors of a vertex. These different visitation orders tend not
606 Chapter 22 Elementary Graph Algorithms
to cause problems in practice, as we can usually use any depth-first search result
effectively, with essentially equivalent results.
What is the running time of DFS? The loops on lines 1–3 and lines 5–7 of DFS
take time ‚.V /, exclusive of the time to execute the calls to DFS-V ISIT. As we did
for breadth-first search, we use aggregate analysis. The procedure DFS-V ISIT is
called exactly once for each vertex 2 V , since the vertex u on which DFS-V ISIT
is invoked must be white and the first thing DFS-V ISIT does is paint vertex u gray.
During an execution of DFS-V ISIT .G; /, the loop on lines 4–7 executes jAdjŒj
times. Since
X
jAdjŒj D ‚.E/ ;
2V
the total cost of executing lines 4–7 of DFS-V ISIT is ‚.E/. The running time of
DFS is therefore ‚.V C E/.
+)!(-!"'-+'-
@"+IQQQ9"-:,%(-
" +'(09A
%#&
"--"(' +)!(
%"-++2-!(+2
&"))+,
%#&
!(+-"%(&).-+
"'&"
(&&.'"-",
&(!+(',!+-+
%#& '-+-"('-0(+$
%#& #-%. %" !-,
%#& (&)%1"-2((
('-"'&'- +)!
%#& "' )''2@,.A +)!
%#&
&&" +-"('
%(0,
%#& (--(-+
%#&
(2',
-+
%#&
+)!"%&(%,
%#&
!--,0!-"'
-!-%'-"('5
%#& .+%(''-"(',
"'-!+"'
%#&
" !*
0'--(',0+*.,-"(',(.--!&8
""'-+(.-"' 5
(&&.'"-2--"('=%.,-+"' 5
'(++"' -!-+,)-,)''",5
!",",0!-0:%%((+-!'1-,/+%%-.+,8
!%'%#& J
,/+-", ' , I
",-!,-(/+-",
",-!,-( , K
(+&%%26 +)!",S@6A
S@6A
1&)% L
SDI6J6K6LE
SDDI6KE6DJ6LE6DK6LE6DJ6KEE
,/+-", ' , I
",-!,-(/+-",
",-!,-( , K
(+&%%26 +)!",S@6A
S@6A
1&)% L
SDI6J6K6LE
SD@I6KA6@J6LA6@K6LA6@L6KA6@K6JAE
!"'> + (/+-1L",28
!(.-> + (/+-1L",I8
+-1L:, "'(&"' '" !(+,+J
and 3
+-1L:,(.- ("' '" !(+ ",K8
"*"*%#%&!'%#&.
)-"('I7#'2&-+"1
J
IJKL I
K
IJKL
L
"*"*%#%&!'%#&.
)-"('I7#'2&-+"1
J
IJKL I
K
IJKL
L
"*"*%#%&!'%#&.
)-"('I7#'2&-+"1 J
,-"'-"('
I
IJKL
K
(.+
IJKL
L
"*"*%#%&!'%#&.
)-"('J7%"'$%",-,8
J
I J K L
I
K
K L I J L
K L K (00(.%2(.
&("2-!",(+
L:,'" !(+,+
"+- +)!,55
J'K
!'%&
2-!"'$(/+-",,-(+"' (-!+"'(+&-"('
--+".-,@'&6 +,,69A
!%)+"'((+% (+"-!&,-!-00"%%)+(+&('-!
+)!
0"%%0'--(%-((-!(%%(0"' (),7
&+,!")7 , "'5
" !(+.+27!-+-!'" !(+,(/+-1/5
%5"& I J K L
2-!++'/+-", K L I J
'& ,8
K L K
" !(+*.+2
"/&/:,'" !(+,8
@'A @ @/AA
)+*."+&'-,
@'JA @'R&A
+!!#"!
!""
" !""!!
Graphs
• A graph G = (V, E)
– V = set of vertices
– E = set of edges = subset of V × V
– Thus |E| = O(|V|2)
1 Vertices: {1, 2, 3, 4}
Edges: {(1, 2), (2, 3), (1, 3), (4, 3)}
2 4
3
Graph Variations (1)
• Directed / undirected:
– In an undirected graph:
• Edge (u,v) ∈ E implies edge (v,u) ∈ E
• Road networks between cities
– In a directed graph:
• Edge (u,v): u→v does not imply v→u
• Street networks in downtown
– Degree of vertex v:
• The number of edges adjacency to v
• For directed graph, there are in-degree and out-degree
1 1
2 4 2 4
3 In-degree = 3 3 Degree = 3
Out-degree = 0
Directed Undirected
Graph Variations (2)
• Weighted / unweighted:
– In a weighted graph, each edge or vertex has an
associated weight (numerical value)
• E.g., a road map: edges might be weighted w/ distance
1 1
0.3
2 4 2 1.2 4
0.4 1.9
3 3
Unweighted Weighted
Graph Variations (4)
• Dense / sparse:
– Graphs are sparse when the number of edges is
linear to the number of vertices
• |E| ∈ O(|V|)
– Graphs are dense when the number of edges is
quadratic to the number of vertices
• |E| ∈ O(|V|2)
– Most graphs of interest are sparse
– If you know you are dealing with dense or sparse
graphs, different data structures may make sense
Representing Graphs
• Assume V = {1, 2, …, n}
• An adjacency matrix represents the graph as a n
x n matrix A:
– A[i, j] = 1 if edge (i, j) ∈ E
= 0 if edge (i, j) ∉ E
• For weighted graph
– A[i, j] = wij if edge (i, j) ∈ E
= 0 if edge (i, j) ∉ E
• For undirected graph
– Matrix is symmetric: A[i, j] = A[j, i]
Graphs: Adjacency Matrix
• Example:
A 1 2 3 4
1
1
2 4 2
3
??
3 4
Graphs: Adjacency Matrix
• Example:
A 1 2 3 4
1
1 0 1 1 0
2 4 2 0 0 1 0
3 0 0 0 0
3 4 0 0 1 0
2 4 2 1 0 1 0
3 1 1 0 1
3 4 0 0 1 0
Undirected graph
Graphs: Adjacency Matrix
• Example:
A 1 2 3 4
1
5 1 0 5 6 0
2 6
4 2 5 0 9 0
9 4 3 6 9 0 4
3 4 0 0 4 0
Weighted graph
Graphs: Adjacency Matrix
• Time to answer if there is an edge
between vertex u and v: Θ(1)
• Memory required: Θ(n2) regardless of |E|
– Usually too much storage for large graphs
– But can be very efficient for small graphs
• Most large interesting graphs are sparse
– E.g., road networks (due to limit on junctions)
– For this reason the adjacency list is often a
more appropriate representation
Graphs: Adjacency List
• Adjacency list: for each vertex v ∈ V, store a list
of vertices adjacent to v
• Example:
– Adj[1] = {2,3}= deg(1) 1
– Adj[2] = {3} = deg(2)
– Adj[3] = {} = deg(3) 2 4
– Adj[4] = {3} = deg(4)
• Variation: can also keep
3
a list of edges coming into vertex
Graph representations
• Adjacency list
1
2 3
3
2 4
3
3,4
Graphs: Adjacency List
• How much storage is required?
• For directed graphs
– |adj[v]| = out-degree(v)
– Total # of items in adjacency lists is
Σ out-degree(v) = |E|
• For undirected graphs
– |adj[v]| = degree(v)
– # items in adjacency lists is
Σ degree(v) = 2 |E|
• So: Adjacency lists take Θ(V+E) storage
• Time needed to test if edge (u, v) ∈ E is O(n)