Start with distance(1)=0 and queue [1].
Week 09 · Lectures 10, 11
Graph representations and BFS
Represent networks with adjacency lists or matrices. Use a queue to discover vertices in increasing number of edges from the start.
Read alongside the document
Use the lecture headings below in the English–Turkish notes. Document lecture numbers and course week numbers are different.
- Lecture 10: Graph Data Structures
What a graph is; Flavours of graphs; The friendship graph: vocabulary through an example; Storing a graph: adjacency matrix; Storing a graph: adjacency lists; Which one to use; The adjacency-list implementation used in the course. - Lecture 11: Breadth-First Search
Warm-up: converting between graph representations; Traversal: the general idea; BFS; The BFS tree and shortest paths; Application: connected components; Application: two-colouring (bipartite graphs).
Why does BFS find the shortest unweighted path?
Undirected edges: 1–2,1–3,2–4,3–4,4–5. Run BFS from 1, considering neighbours in increasing order.
Process 1: discover 2 and 3 at distance 1; queue [2,3].
Process 2: discover 4 at distance 2. Processing 3 does not rediscover 4.
Process 4: discover 5 at distance 3. Discovery order is 1,2,3,4,5; one shortest path is 1–2–4–5.
Change the case. BFS minimises edge count; arbitrary edge weights need a different algorithm. Mark vertices when enqueued to avoid repeated insertion.
Explain before coding
State the input and required output. Trace a small example. Explain why each step is valid, count the work under a stated model, and test an edge case.
Python support for this week
A dictionary of neighbour lists represents a graph. A deque supports efficient queue removal from the front.
from collections import deque
g = {1:[2,3], 2:[1,4], 3:[1,4], 4:[2,3,5], 5:[4]}
q = deque([1]); distance = {1:0}
while q:
u = q.popleft()
for v in g[u]:
if v not in distance:
distance[v] = distance[u] + 1
q.append(v)
print(distance) # {1:0, 2:1, 3:1, 4:2, 5:3}Run this small demonstration after predicting its result. It illustrates the selected example; its input assumptions are part of the example.
Open the optional Python support library. Programming fluency is not required to complete the paper trace.
Read the related bilingual explanations here
Sections from the supplied lecture notes. Turkish paragraphs appear in red. Use this as a reference after the worked example.
Lecture 10 · What a graph is
Çizge nedir?
A graph G = (V, E) consists of a set V of vertices and a set E of edges, where each edge is a pair of vertices. Examples:
G = (V, E) çizgesi, V tepeler kümesi ile E kenarlar kümesinden oluşur; her kenar bir tepe çiftidir. Örnekler:
Road networks: vertices are cities or junctions, edges are roads (the slide shows Stony Brook, Riverhead, Greenport, Montauk and other Long Island towns).
Yol ağları: tepeler şehirler veya kavşaklar, kenarlar yollardır (slaytta Stony Brook, Riverhead, Greenport, Montauk ve Long Island’daki diğer yerleşimler gösterilir).
Electronic circuits: junctions are vertices, components are edges.
Elektronik devreler: bağlantı noktaları tepe, devre elemanları kenardır.
Social networks, the World Wide Web (pages and links), control flow inside a program, and similarity graphs where an edge means two items are alike.
Sosyal ağlar, World Wide Web (sayfalar ve bağlantılar), program içindeki kontrol akışı ve bir kenarın iki nesnenin benzer olduğunu belirttiği benzerlik çizgeleri.
Throughout the course n is the number of vertices and m the number of edges.
Ders boyunca n tepe sayısını, m ise kenar sayısını gösterir.
Lecture 10 · Flavours of graphs
Çizge türleri
Skiena: “learning to talk the talk is an important part of walking the walk.” The flavour decides which algorithms apply.
Skiena: “Bir işin dilini öğrenmek, o işi yapabilmenin önemli bir parçasıdır.” Hangi algoritmaların uygulanabileceğini çizgenin türü belirler.
| Distinction | Meaning | Example |
| Ayrım | Anlamı | Örnek |
| Directed vs. undirected | Undirected: edge (x, y) implies edge (y, x); the line has no arrow. Directed: edges are one-way arrows. | Roads between cities are undirected; streets within a city are directed because of one-way streets. |
| Yönlü / yönsüz | Yönsüz: (x, y) kenarı (y, x) kenarını da ifade eder; çizginin oku yoktur. Yönlü: kenarlar tek yönlü oklardır. | Şehirler arasındaki yollar yönsüzdür; şehir içi sokaklar, tek yönlü sokaklar nedeniyle yönlüdür. |
| Weighted vs. unweighted | Weighted: each edge (or vertex) carries a number. Unweighted: all edges are alike. | Road edges weighted by length, drive time or speed limit. |
| Ağırlıklı / ağırlıksız | Ağırlıklı: her kenar (veya tepe) bir sayı taşır. Ağırlıksız: bütün kenarlar eşdeğerdir. | Uzunluk, sürüş süresi veya hız sınırıyla ağırlıklandırılmış yol kenarları. |
| Simple vs. non-simple | Simple: no self-loops (an edge from x to x) and no multi-edges (the same pair joined twice). | “Are you your own friend?” is a self-loop question. |
| Basit / basit olmayan | Basit: öz döngü (x’ten x’e bir kenar) ve çoklu kenar (aynı çiftin iki kez bağlanması) yoktur. | “Kendinizin arkadaşı mısınız?” bir öz döngü sorusudur. |
| Sparse vs. dense | Sparse: only a small fraction of the possible n(n−1)/2 pairs are joined, so m is roughly linear in n. Dense: m is roughly quadratic. | Road networks are sparse because a junction only meets a few roads. |
| Seyrek / yoğun | Seyrek: olası n(n−1)/2 çiftin yalnızca küçük bir bölümü bağlıdır; dolayısıyla m, n’ye göre yaklaşık doğrusaldır. Yoğun: m yaklaşık kareseldir. | Bir kavşakta yalnızca birkaç yol birleştiği için yol ağları seyrektir. |
| Cyclic vs. acyclic | Acyclic: no cycles at all. A tree is a connected acyclic undirected graph. A directed acyclic graph is a DAG. | DAGs model scheduling, where an edge (x, y) means x must happen before y. |
| Döngülü / döngüsüz | Döngüsüz: hiç döngü yoktur. Ağaç, bağlı, döngüsüz ve yönsüz bir çizgedir. Yönlü döngüsüz çizge, DAG olarak adlandırılır. | DAG’ler çizelgelemeyi modeller; (x, y) kenarı, x’in y’den önce gerçekleşmesi gerektiğini belirtir. |
| Embedded vs. topological | Embedded: vertices and edges have geometric positions that matter. Topological: only the connections matter. | Points in the plane for the travelling salesman; grid graphs; planar graphs. |
| Gömülü / topolojik | Gömülü: tepe ve kenarların önem taşıyan geometrik konumları vardır. Topolojik: yalnızca bağlantılar önemlidir. | Gezgin satıcı için düzlemdeki noktalar; ızgara çizgeleri; düzlemsel çizgeler. |
Lecture 10 · The friendship graph: vocabulary through an example
Arkadaşlık çizgesi: Bir örnek üzerinden terimler
Let the vertices be people and join two people by an edge if they are friends. Asking natural questions about it introduces the standard terms:
Tepeler insanlar olsun; iki insan arkadaşsa aralarını bir kenarla birleştirin. Bu yapı hakkında doğal sorular sormak, standart terimleri tanıtır:
If I am your friend, are you mine? That is asking whether the graph is undirected. The “has heard of” graph is directed (famous people have not heard of Skiena); other relationships are necessarily symmetric.
Ben sizin arkadaşınızsam siz de benim arkadaşım mısınız? Bu, çizgenin yönsüz olup olmadığını sorar. “Adını duymuş olma” çizgesi yönlüdür (ünlü insanlar Skiena’nın adını duymamıştır); başka ilişkiler ise zorunlu olarak simetriktir.
Am I linked by a chain of friends to a celebrity? A path is a sequence of edges connecting two vertices. Since a short chain is more impressive than a long one, we care about the shortest path.
Bir arkadaş zinciriyle bir ünlüye bağlı mıyım? Yol, iki tepeyi bağlayan bir kenar dizisidir. Kısa bir zincir uzun olandan daha etkileyici olduğundan en kısa yolla ilgileniriz.
Is there a chain between any two people at all? A graph is connected if there is a path between every pair of vertices. A directed graph is strongly connected if there is a directed path both ways between every pair. “Six degrees of separation” presumes the world’s friendship graph is connected.
Herhangi iki insan arasında bir zincir var mı? Her tepe çifti arasında bir yol varsa çizge bağlıdır. Yönlü bir çizgede her çift arasında her iki yönde de yönlü bir yol varsa çizge güçlü bağlıdır. “Altı derecelik ayrılık” düşüncesi, dünyanın arkadaşlık çizgesinin bağlı olduğunu varsayar.
Who has the most friends? The degree of a vertex is the number of edges touching it.
En çok kimin arkadaşı var? Bir tepenin derecesi, ona değen kenarların sayısıdır.
What is the largest group of mutual friends? A clique is a set of vertices every pair of which is joined; the densest possible subgraph. In a friendship graph, big cliques are workplaces, schools, congregations.
Herkesin birbiriyle arkadaş olduğu en büyük grup hangisidir? Klik, her çifti birbirine bağlı bir tepeler kümesidir; mümkün olan en yoğun alt çizgedir. Arkadaşlık çizgesinde büyük klikler iş yerleri, okullar ve cemaatlerdir.
Lecture 10 · Storing a graph: adjacency matrix
Çizgeyi saklama: Komşuluk matrisi
Use an n × n table M where M[i, j] = 1 if (i, j) is an edge and 0 otherwise. Checking whether an edge exists is one lookup. The cost is space: n² entries even when the graph has only a few edges. An undirected graph could store only half the matrix (it is symmetric), but a sparse graph still wastes almost all of it.
M[i, j], (i, j) bir kenarsa 1, değilse 0 olacak şekilde n × n boyutlu bir M tablosu kullanın. Bir kenarın varlığını denetlemek tek bir erişim gerektirir. Bedeli bellek alanıdır: çizgede yalnızca birkaç kenar olsa bile n² hücre. Yönsüz çizgede matrisin yalnızca yarısı saklanabilir (matris simetriktir), ancak seyrek bir çizgede bunun da neredeyse tamamı boşa gider.
Lecture 10 · Storing a graph: adjacency lists
Çizgeyi saklama: Komşuluk listeleri
Keep an array of n pointers; entry i points to a linked list of the vertices adjacent to i. The slide’s example has vertex 1 adjacent to 2 and 5; vertex 2 to 1, 5, 4, 3; vertex 3 to 2 and 4; vertex 4 to 5, 2, 3; vertex 5 to 1, 2, 4. Notice that every undirected edge appears twice, once in each endpoint’s list.
n işaretçiden oluşan bir dizi tutun; i. giriş, i’ye komşu tepelerin bağlı listesine işaret etsin. Slayttaki örnekte 1 tepesi 2 ve 5’e; 2 tepesi 1, 5, 4, 3’e; 3 tepesi 2 ve 4’e; 4 tepesi 5, 2, 3’e; 5 tepesi 1, 2, 4’e komşudur. Her yönsüz kenarın, uçlarının her birinin listesinde birer kez olmak üzere iki kez yer aldığına dikkat edin.
To test whether edge (i, j) exists, scan list i for j, which costs O(dᵢ), the degree of i. In a sparse graph dᵢ is much smaller than n. If deletions are needed, the two copies of an edge can be linked to each other by a pointer.
(i, j) kenarının varlığını sınamak için i listesini j’yi arayarak tarayın; bunun maliyeti i’nin derecesi olan O(dᵢ)’dir. Seyrek çizgede dᵢ, n’den çok küçüktür. Silme işlemleri gerekiyorsa bir kenarın iki kopyası bir işaretçiyle birbirine bağlanabilir.
Lecture 10 · Which one to use
Hangisini kullanmalı?
| Question | Winner |
| Soru | Üstün olan |
| Faster to test whether edge (x, y) exists? | Matrix |
| (x, y) kenarının varlığını sınamada daha hızlı olan? | Matris |
| Faster to find a vertex’s degree? | Lists |
| Bir tepenin derecesini bulmada daha hızlı olan? | Listeler |
| Less memory on small graphs? | Lists, O(m + n) versus O(n²) |
| Küçük çizgelerde daha az bellek kullanan? | Listeler: O(n²) yerine O(m + n) |
| Less memory on big dense graphs? | Matrix, slightly (no pointers) |
| Büyük ve yoğun çizgelerde daha az bellek kullanan? | Az farkla matris (işaretçi yok) |
| Edge insertion or deletion? | Matrix, O(1) |
| Kenar ekleme veya silme? | Matris, O(1) |
| Faster to traverse the whole graph? | Lists, O(m + n) versus O(n²) |
| Bütün çizgeyi dolaşmada daha hızlı olan? | Listeler: O(n²) yerine O(m + n) |
| Better for most problems? | Lists |
| Çoğu problem için daha iyi olan? | Listeler |
Both are useful, but adjacency lists win for most problems because most real graphs are sparse and most algorithms traverse rather than look up specific edges. The rest of the course assumes adjacency lists.
İkisi de yararlıdır; fakat gerçek çizgelerin çoğu seyrek ve algoritmaların çoğu belirli kenarları aramak yerine dolaşım yaptığı için komşuluk listeleri çoğu problemde üstündür. Dersin geri kalanında komşuluk listeleri varsayılır.
Lecture 10 · The adjacency-list implementation used in the course
Derste kullanılan komşuluk listesi gerçeklemesi
Each edge is a small record and each vertex owns a list of them:
Her kenar küçük bir kayıttır ve her tepe bu kayıtların bir listesine sahiptir:
edgenode:
y (the other endpoint)
weight (edge weight, if any)
next (next edge in this vertex's list)
graph:
edges[1..n] (edges[i] = head of vertex i's list)
degree[1..n] (number of edges out of each vertex)
nvertices, nedges
directed (true or false)edgenode:
y (diğer uç tepe)
weight (varsa kenar ağırlığı)
next (bu tepenin listesindeki sonraki kenar)
graph:
edges[1..n] (edges[i] = i tepesinin listesinin başı)
degree[1..n] (her tepeden çıkan kenar sayısı)
nvertices, nedges
directed (true veya false)Reading a graph from a file: the first line gives n and m, then one edge per line. Each edge is inserted at the head of its list in O(1):
Dosyadan çizge okuma: İlk satır n ve m’yi verir; ardından her satırda bir kenar bulunur. Her kenar, kendi listesinin başına O(1) sürede eklenir:
insert_edge(g, x, y, directed):
create an edgenode p with p.y = y, p.weight = 0
p.next = g.edges[x]
g.edges[x] = p (insert at head of x's list)
g.degree[x] = g.degree[x] + 1
if not directed:
insert_edge(g, y, x, true) (add the reverse copy)
else:
g.nedges = g.nedges + 1insert_edge(g, x, y, directed):
p.y = y, p.weight = 0 olan bir edgenode p oluştur
p.next = g.edges[x]
g.edges[x] = p (x listesinin başına ekle)
g.degree[x] = g.degree[x] + 1
if not directed:
insert_edge(g, y, x, true) (ters kopyayı ekle)
else:
g.nedges = g.nedges + 1The recursive trick at the end adds the reverse edge for undirected graphs without counting the edge twice.
Sondaki özyineleme tekniği, yönsüz çizgelerde kenarı iki kez saymadan ters kenarı ekler.
Lecture 11 · Warm-up: converting between graph representations
Hazırlık: Çizge gösterimleri arasında dönüşüm
For an undirected graph with n vertices and m edges:
n tepeli ve m kenarlı yönsüz bir çizge için:
Adjacency matrix → adjacency lists. Scan every matrix entry; each 1 becomes a list insertion. O(n²), because the matrix has to be read whole.
Komşuluk matrisi → komşuluk listeleri. Matrisin bütün hücrelerini tarayın; her 1, listeye bir ekleme işlemine dönüşür. Matrisin tamamı okunmak zorunda olduğundan O(n²).
Adjacency lists → incidence matrix. (An incidence matrix has a row per vertex and a column per edge, with a 1 where the vertex is an endpoint of that edge.) Walk the lists, giving each edge a column number as it is met and marking its two endpoints. Creating the matrix costs O(nm) just to zero it out, which dominates.
Komşuluk listeleri → geliş matrisi. (Geliş matrisinde her tepe için bir satır, her kenar için bir sütun vardır; tepe kenarın uçlarından biriyse hücre 1’dir.) Listeleri dolaşın; karşılaştığınız her kenara bir sütun numarası verin ve iki ucunu işaretleyin. Matrisi oluştururken yalnızca sıfırlamak bile O(nm) maliyetlidir ve baskın terim budur.
Incidence matrix → adjacency lists. Each column has exactly two 1s; scan each column to find them and insert the edge. O(nm) for scanning the whole matrix.
Geliş matrisi → komşuluk listeleri. Her sütunda tam iki tane 1 vardır; bunları bulmak için her sütunu tarayın ve kenarı ekleyin. Matrisin tamamını taramak O(nm) sürer.
The theme: a representation costs at least its own size to read or write, so the matrix representations impose their size on every conversion.
Ana fikir: Bir gösterimi okumak veya yazmak en az kendi boyutu kadar maliyetlidir; bu nedenle matris gösterimleri her dönüşüme kendi boyutlarının maliyetini yükler.
Lecture 11 · Traversal: the general idea
Dolaşım: Genel fikir
One of the most basic graph problems is to visit every vertex and edge. Two requirements: for efficiency, visit each edge at most twice (once from each endpoint); for correctness, be systematic enough not to miss anything. A maze is a graph, so a traversal algorithm has to be at least strong enough to get you out of any maze.
En temel çizge problemlerinden biri, her tepe ve kenarı ziyaret etmektir. İki gereklilik vardır: verimlilik için her kenarı en fazla iki kez (her ucundan bir kez) ziyaret etmek; doğruluk için hiçbir şeyi atlamayacak kadar sistematik olmak. Labirent bir çizgedir; dolayısıyla dolaşım algoritması sizi herhangi bir labirentten çıkarabilecek kadar güçlü olmalıdır.
The key idea is to mark vertices as they are found. Every vertex is always in one of three states, and only ever moves forward through them:
Temel fikir, tepeleri bulundukça işaretlemektir. Her tepe her zaman üç durumdan birindedir ve bu durumlar arasında yalnızca ileri yönde hareket eder:
Undiscovered: never seen.
Keşfedilmemiş: Hiç görülmemiş.
Discovered: seen, but not all of its edges have been examined yet.
Keşfedilmiş: Görülmüş, fakat bütün kenarları henüz incelenmemiş.
Processed: all of its edges have been examined.
İşlenmiş: Bütün kenarları incelenmiş.
We keep a “to-do list” of vertices that are discovered but not yet processed. At the start only the start vertex is discovered. To process a vertex, look at each edge leaving it; whenever an edge leads to an undiscovered vertex, mark that vertex discovered and add it to the to-do list.
Keşfedilmiş ama henüz işlenmemiş tepelerin bir “yapılacaklar listesini” tutarız. Başlangıçta yalnızca başlangıç tepesi keşfedilmiştir. Bir tepeyi işlemek için ondan çıkan her kenara bakın; bir kenar keşfedilmemiş tepeye ulaştığında o tepeyi keşfedilmiş olarak işaretleyin ve yapılacaklar listesine ekleyin.
Whatever order we take vertices from the to-do list, each edge is looked at exactly twice, once from each endpoint. That order is the only difference between BFS and DFS: BFS keeps the to-do list as a queue (first found, first processed); DFS keeps it as a stack.
Tepeleri yapılacaklar listesinden hangi sırayla alırsak alalım, her kenara her ucundan birer kez olmak üzere tam iki kez bakılır. BFS ve DFS arasındaki tek fark bu sıradır: BFS yapılacaklar listesini kuyruk olarak (ilk bulunan, ilk işlenen), DFS ise yığın olarak tutar.
Correctness. Every vertex and edge in the start vertex’s connected component is eventually visited. Suppose some vertex u were never visited but had a neighbour v that was. Then v was at some point processed, its edges were examined, and the edge to u would have discovered u. Contradiction.
Doğruluk. Başlangıç tepesinin bağlı bileşenindeki her tepe ve kenar sonunda ziyaret edilir. Bir u tepesinin hiç ziyaret edilmediğini, fakat v komşusunun ziyaret edildiğini varsayın. O hâlde v bir noktada işlenmiş, kenarları incelenmiş ve u’ya giden kenar u’yu keşfetmiş olmalıydı. Çelişki.
Lecture 11 · BFS
BFS
BFS uses two boolean arrays, discovered and processed, plus a parent array recording which vertex discovered each vertex. Discovered vertices wait in a FIFO queue, so the oldest, which are closest to the start, are expanded first.
BFS, discovered ve processed adlı iki Boole dizisi ile her tepeyi hangi tepenin keşfettiğini kaydeden parent dizisini kullanır. Keşfedilen tepeler bir FIFO kuyruğunda bekler; bu nedenle başlangıca en yakın olan, en önce keşfedilmiş tepeler önce genişletilir.
bfs(G, start):
queue q = {start}; discovered[start] = true
while q is not empty:
v = dequeue(q)
process_vertex_early(v)
processed[v] = true
for each edge (v, y):
if not processed[y] or G is directed:
process_edge(v, y)
if not discovered[y]:
enqueue(q, y)
discovered[y] = true
parent[y] = v
process_vertex_late(v)bfs(G, start):
q kuyruğu = {start}; discovered[start] = true
while q boş değilse:
v = dequeue(q)
process_vertex_early(v)
processed[v] = true
for her (v, y) kenarı:
if not processed[y] or G yönlü ise:
process_edge(v, y)
if not discovered[y]:
enqueue(q, y)
discovered[y] = true
parent[y] = v
process_vertex_late(v)The test not processed[y] stops an undirected edge being processed twice (it is seen from both ends). The three hooks process_vertex_early, process_edge and process_vertex_late are deliberately left empty: filling them in customises the traversal. Set them to print, and you print each vertex and each edge exactly once.
not processed[y] sınaması, yönsüz bir kenarın iki kez işlenmesini engeller (kenar her iki ucundan da görülür). process_vertex_early, process_edge ve process_vertex_late adlı üç uyarlama noktası bilinçli olarak boş bırakılmıştır; bunları doldurmak dolaşımı özelleştirir. Yazdırma yapacak şekilde tanımlarsanız her tepeyi ve her kenarı tam bir kez yazdırırsınız.
Cost. Each vertex is enqueued and dequeued once, and each edge is looked at twice: O(n + m) with adjacency lists.
Maliyet. Her tepe bir kez kuyruğa eklenir ve bir kez çıkarılır; her kenara iki kez bakılır: komşuluk listeleriyle O(n + m).
Lecture 11 · The BFS tree and shortest paths
BFS ağacı ve en kısa yollar
The parent array defines a tree, rooted at the start vertex, with an edge from each vertex to the vertex that discovered it. This is the BFS tree.
parent dizisi, kökü başlangıç tepesi olan ve her tepeden onu keşfeden tepeye bir kenar içeren bir ağaç tanımlar. Bu, BFS ağacıdır.
Because BFS discovers vertices in order of increasing distance from the root, the BFS tree has a precious property: the tree path from the root to any vertex x uses the fewest possible edges of any path in the graph. That is, BFS computes shortest paths when every edge counts as 1. (For edges with different lengths, wait for Dijkstra in Lecture 14.)
BFS tepeleri kökten artan uzaklık sırasıyla keşfettiği için BFS ağacının değerli bir özelliği vardır: kökten herhangi bir x tepesine giden ağaç yolu, çizgedeki bütün yollar arasında mümkün olan en az sayıda kenarı kullanır. Yani her kenar 1 sayıldığında BFS en kısa yolları hesaplar. (Uzunlukları farklı kenarlar için Ders 14’teki Dijkstra algoritmasını bekleyin.)
Reconstructing the path. Parent pointers point towards the root, so you can only walk from x back to the root, not the other way. Walk backwards, or let recursion reverse the order for you:
Yolu yeniden oluşturma. Ebeveyn işaretçileri köke doğru yönelir; bu yüzden yalnızca x’ten köke geri yürüyebilirsiniz, tersi yönde değil. Geriye doğru yürüyün veya özyinelemenin sırayı sizin için tersine çevirmesine izin verin:
find_path(start, end, parent):
if start == end or end == −1:
print start
else:
find_path(start, parent[end], parent)
print endfind_path(start, end, parent):
if start == end or end == −1:
print start
else:
find_path(start, parent[end], parent)
print endThe recursive call happens before printing, so the printing comes out root-first.
Özyinelemeli çağrı yazdırmadan önce gerçekleştiği için çıktı kökten başlayarak üretilir.
Lecture 11 · Application: connected components
Uygulama: Bağlı bileşenler
The connected components of an undirected graph are its separate pieces: sets of vertices with paths inside each set and no edges between sets. Many complicated-looking questions are really component questions. “Can a Rubik’s cube (or the 15-puzzle) be solved from every position?” asks whether the graph of legal positions, with edges for legal moves, is connected.
Yönsüz bir çizgenin bağlı bileşenleri, birbirinden ayrı parçalarıdır: her kümenin içinde yollar bulunan, fakat kümeler arasında kenar bulunmayan tepe kümeleri. Karmaşık görünen birçok soru aslında bir bileşen sorusudur. “Rubik küpü (veya 15 bulmacası) her konumdan çözülebilir mi?” sorusu, geçerli konumların tepe, geçerli hamlelerin kenar olduğu çizgenin bağlı olup olmadığını sorar.
Everything discovered by one BFS lies in the same component. So: run BFS from vertex 1, label everything it reaches as component 1; find the next undiscovered vertex and run BFS from it for component 2; repeat until every vertex is discovered.
Tek bir BFS’nin keşfettiği her şey aynı bileşendedir. Dolayısıyla 1 tepesinden BFS çalıştırın ve ulaştığı her şeyi bileşen 1 olarak etiketleyin; keşfedilmemiş sonraki tepeyi bulun ve bileşen 2 için oradan BFS başlatın; bütün tepeler keşfedilene kadar tekrarlayın.
connected_components(G):
c = 0
for each vertex i:
if not discovered[i]:
c = c + 1
print "Component", c
bfs(G, i) (with process_vertex_early printing the vertex)connected_components(G):
c = 0
for her i tepesi:
if not discovered[i]:
c = c + 1
print "Bileşen", c
bfs(G, i) (process_vertex_early tepeyi yazdırır)Total cost O(n + m), since each vertex and edge is touched once over all the searches.
Bütün aramalar boyunca her tepe ve kenara bir kez dokunulduğu için toplam maliyet O(n + m)’dir.
Lecture 11 · Application: two-colouring (bipartite graphs)
Uygulama: İki renkle boyama (iki parçalı çizgeler)
Vertex colouring assigns a colour to each vertex so that no edge joins two vertices of the same colour. A graph that can be coloured with only two colours is bipartite. Bipartite graphs are common: students and the courses they take form one (edges only go between a student and a course, never student-student or course-course).
Tepe boyama, hiçbir kenar aynı renkte iki tepeyi birleştirmeyecek biçimde her tepeye bir renk atar. Yalnızca iki renkle boyanabilen çizge iki parçalıdır. İki parçalı çizgeler yaygındır: öğrenciler ve aldıkları dersler böyle bir çizge oluşturur (kenarlar yalnızca öğrenciyle ders arasındadır; öğrenci–öğrenci veya ders–ders arasında asla değildir).
BFS finds a two-colouring, or proves there is none: whenever a vertex is discovered, colour it the opposite of its parent. Every processed edge is checked; if its endpoints have the same colour the graph is not bipartite.
BFS iki renkli bir boyama bulur veya böyle bir boyama olmadığını kanıtlar: her tepe keşfedildiğinde onu ebeveyninin karşıt rengine boyayın. İşlenen her kenar denetlenir; uçları aynı renkteyse çizge iki parçalı değildir.
twocolor(G):
colour every vertex UNCOLOURED; bipartite = true
for each vertex i:
if not discovered[i]:
colour[i] = WHITE
bfs(G, i)
process_edge(x, y):
if colour[x] == colour[y]:
bipartite = false; report the offending edge (x, y)
colour[y] = complement(colour[x])twocolor(G):
her tepenin rengini UNCOLOURED yap; bipartite = true
for her i tepesi:
if not discovered[i]:
colour[i] = WHITE
bfs(G, i)
process_edge(x, y):
if colour[x] == colour[y]:
bipartite = false; ihlal eden (x, y) kenarını bildir
colour[y] = complement(colour[x])The first vertex of each component can be given whichever colour we like; the rest is forced. Cost: O(n + m).
Her bileşenin ilk tepesine istediğimiz rengi verebiliriz; geri kalan renkler zorunlu olarak belirlenir. Maliyet: O(n + m).
Begin with the easy tests and the worked example. Remaining questions provide repeated teaching practice; hard questions are optional depth. Some tests revisit earlier prerequisites. Answers stay visible.
Practice with answers
10 test questions · 11 written questions · 21 total
Each question is followed by its answer and explanation. Hard questions also include a starting hint and smaller reasoning steps.
Test questions
Choose one option. Cost questions state their model and whether the bound is tight, expected or worst-case. Here lg means log₂, and heap positions start at 1.
Question 1 · easy
The maximum number of edges in a simple undirected graph on 5 vertices is:
Answer: option B. n(n − 1)/2 = 5 × 4 / 2.
Question 2 · easy
An undirected graph has 7 edges. The degrees of its vertices add up to:
Answer: option B. Every edge is counted once at each of its two endpoints.
Question 3 · easy
For an n-vertex graph, what is the tightest listed worst-case space bound for a full adjacency matrix?
Answer: option B. One entry per pair of vertices, edge or not.
Question 4 · easy
Breadth-first search keeps its discovered-but-unprocessed vertices in:
Answer: option B. First found, first processed, which is why it expands by distance.
Question 5 · easy
Shortest paths in an unweighted graph are found by:
Answer: option A. The BFS tree path to each vertex uses the fewest possible edges.
Question 6 · easy
A tree with 12 vertices has how many edges?
Answer: option A. Always n − 1.
Question 7 · easy
A triangle (three mutually adjacent vertices) is:
Answer: option B. It is an odd cycle, and two colours cannot colour it.
Question 8 · easy · course question
In BFS, when should a vertex be marked discovered?
Answer: option A. Marking on enqueue prevents different parents from placing the same vertex into the queue repeatedly.
Question 9 · easy · course question
BFS distance measures what in an unweighted graph?
Answer: option B. BFS processes vertices by levels: all distance-k vertices precede distance-(k+1) vertices.
Question 10 · medium
A graph has edges 1–2, 1–3, 2–4, 3–4, 4–5. BFS from 1, taking neighbours in increasing order, discovers vertices in the order:
Answer: option B. Distance 1 vertices (2, 3) before distance 2 (4) before distance 3 (5).
Written questions
Read each question together with its explanation, trace or proof. Numbering continues from the test questions.
Question 11 · easy
Define the degree of a vertex, a path, and a connected graph.
Answer & reasoning
For a simple undirected graph, degree is the number of incident edges. A path is a vertex sequence whose consecutive vertices are joined by edges; a simple path has no repeated vertices. A graph is connected when every pair of vertices is joined by a path.
Question 12 · easy
What is the maximum number of edges in a simple undirected graph on n vertices? In a simple directed graph (no self-loops)?
Answer & reasoning
n(n − 1)/2, one per unordered pair; n(n − 1), one per ordered pair.
Question 13 · easy
In an undirected graph, what do the degrees of all vertices add up to?
Answer & reasoning
2m, because every edge contributes 1 to the degree of each of its two endpoints.
Question 14 · easy
A graph has edges 1–2, 1–3, 2–4, 3–4, 4–5. Run BFS from vertex 1, taking neighbours in increasing order. In what order are vertices discovered, and what is the distance from 1 to 5?
Answer & reasoning
1, 2, 3, 4, 5. Vertex 5 is at distance 3 (for example 1–2–4–5).
Question 15 · easy
A graph on vertices 1 to 6 has edges 1–2, 2–3 and 4–5. How many connected components does it have?
Answer & reasoning
three: {1, 2, 3}, {4, 5} and {6}. An isolated vertex is a component on its own.
Question 16 · easy
Which traversal finds shortest paths in an unweighted graph, and why does the other one not?
Answer & reasoning
BFS, because it discovers vertices in order of increasing distance from the start. DFS dives deep first and may reach a vertex by a long roundabout route before a short one.
Question 17 · easy
Is a triangle bipartite? Is a 4-cycle (a square)?
Answer & reasoning
the triangle is not: three mutually adjacent vertices cannot be two-coloured. The square is: colour opposite corners alike.
Question 18 · medium
Two-colour the graph with edges 1–2, 2–3, 3–4, 4–1 and 1–3 using BFS from vertex 1. Is it bipartite?
Answer & reasoning
colour 1 white; its neighbours 2, 4 and 3 become black; then the edge 2–3 joins two black vertices. Not bipartite: 1–2–3 is a triangle, an odd cycle.
Question 19 · medium
Given a directed graph in adjacency-list form, compute the in-degree of every vertex in O(n + m).
Answer & reasoning
set in[v] = 0 for all v, then walk every adjacency list once and, for each edge x→y encountered, add 1 to in[y]. Each edge is seen exactly once.
Question 20 · hard · optional challenge
Prove that the path from the root to any vertex in a BFS tree is a shortest path.
In simpler words: Explain why a BFS parent chain uses the fewest edges.
Starting hint: Think of the queue as distance layers 0,1,2,… .
Answer & reasoning
Step by step
- The start is layer 0. Its newly discovered neighbours form layer 1.
- All layer-d vertices leave the queue before any layer-(d+1) vertex is processed.
- A vertex first reached from layer d cannot have a shorter undiscovered route: that route’s earlier layer would already have found it. Its parent chain therefore has shortest length d+1.
claim: BFS discovers all vertices at distance d before any vertex at distance d + 1, and a vertex at distance d + 1 is always discovered from a vertex at distance d. Induction on d: the root is the only vertex at distance 0. Assume the claim up to d. Every vertex at distance d + 1 has a neighbour at distance d; the queue holds all distance-d vertices before any at distance d + 1, so when those are processed each distance-(d + 1) vertex is discovered from a distance-d parent and put in the queue before any distance-(d + 2) vertex. Hence parent pointers step down by exactly one distance unit, and the tree path from the root to v has exactly dist(v) edges.
Question 21 · hard · optional challenge
Prove that a graph is bipartite if and only if it contains no cycle of odd length.
In simpler words: Connect two-colouring with even and odd cycles.
Starting hint: Prove both directions separately.
Answer & reasoning
Step by step
- If an edge always changes colour, a cycle returns to its starting colour only after an even number of edges.
- Conversely, colour BFS levels alternately in each component.
- An edge within the same level would create an odd cycle: take the two tree branches from their last common ancestor, then that edge. With no odd cycle, every edge joins opposite colours.
if it is bipartite, colours alternate along any cycle, so returning to the start colour needs an even number of steps. Conversely, if there is no odd cycle, BFS from a vertex in each component and colour vertices by the parity of their distance. Any edge joins vertices whose distances differ by at most 1; if an edge joined two vertices at the same distance d, the two tree paths to them plus that edge would form a closed walk of length 2d + 1, which contains an odd cycle. So every edge joins different parities: a valid two-colouring.