Breadth First Search (BFS)
Authors: Benjamin Qi, Michael Cao, Andi Qu
Prerequisites
Traversing a graph in a way such that vertices closer to the starting vertex are processed first.
Queues & Deques
Resources | |||
---|---|---|---|
CPH | |||
PAPS |
Queues
A queue is a First In First Out (FIFO) data structure that supports three operations, all in time.
C++
C++
push
: insertion at the back of the queuepop
: deletion from the front of the queuefront
: which retrieves the element at the front without removing it.
1queue<int> q;2q.push(1); // [1]3q.push(3); // [3, 1]4q.push(4); // [4, 3, 1]5q.pop(); // [4, 3]6cout << q.front() << endl; // 3
Java
Java
add
: insertion at the back of the queuepoll
: deletion from the front of the queuepeek
: which retrieves the element at the front without removing it
Java doesn't actually have a Queue
class; it's only an interface. The most commonly used implementation is the LinkedList
, declared as follows:
1Queue<Integer> q = new LinkedList<Integer>();2q.add(1); // [1]3q.add(3); // [3, 1]4q.add(4); // [4, 3, 1]5q.poll(); // [4, 3]6System.out.println(q.peek()); // 3
Deques
A deque (usually pronounced "deck") stands for double ended queue and is a combination of a stack and a queue, in that it supports insertions and deletions from both the front and the back of the deque. Not very common in Bronze / Silver.
C++
C++
The four methods for adding and removing are push_back
, pop_back
, push_front
, and pop_front
.
1deque<int> d;2d.push_front(3); // [3]3d.push_front(4); // [4, 3]4d.push_back(7); // [4, 3, 7]5d.pop_front(); // [3, 7]6d.push_front(1); // [1, 3, 7]7d.pop_back(); // [1, 3]
You can also access deques in constant time like an array in constant time with the []
operator. For example, to access the element for some deque , do .
Java
Java
In Java, the deque class is called ArrayDeque
. The four methods for adding and removing are addFirst
, removeFirst
, addLast
, and removeLast
.
1ArrayDeque<Integer> deque = new ArrayDeque<Integer>();2deque.addFirst(3); // [3]3deque.addFirst(4); // [4, 3]4deque.addLast(7); // [4, 3, 7]5deque.removeFirst(); // [3, 7]6deque.addFirst(1); // [1, 3, 7]7deque.removeLast(); // [1, 3]
Breadth First Search
Focus Problem – read through this problem before continuing!
Resources
Resources | |||
---|---|---|---|
CSA | interactive, implementation | ||
PAPS | grid, 8-puzzle examples | ||
cp-algo | common applications | ||
KA | |||
Youtube | If you prefer a video format |
Solution - Message Route
C++
1int n,m, dist[MX], pre[MX];2vi adj[MX];34int main() {5 setIO(); re(n,m);6 F0R(i,m) {7 int a,b; re(a,b);8 adj[a].pb(b), adj[b].pb(a);9 }10 FOR(i,2,n+1) dist[i] = MOD;
Pro Tip
In the gold division, the problem statement will almost never directly be, "Given an unweighted graph, find the shortest path between node and ." Instead, the difficulty in many BFS problems are converting the problem into a graph on which we can run BFS and get the answer.
0/1 BFS
A 0/1 BFS finds the shortest path in a graph where the weights on the edges can only be 0 or 1, and runs in using a deque. Read the resource below for an explanation of how the algorithm works.
Resources | |||
---|---|---|---|
cp-algo | common applications |
Focus Problem – read through this problem before continuing!
Consider the graph with an edge between each pair of adjacent cells with tracks, where the weight is 0 if the tracks are the same and 1 otherwise. The answer is simply the longest shortest-path from the top left cell.
Since the weight of each edge is either 0 or 1 and we want the shortest paths from the top left cell to each other cell, we can apply 0/1 BFS. The time complexity of this solution is .
C++
1#include <bits/stdc++.h>2using namespace std;34int dx[4]{1, -1, 0, 0}, dy[4]{0, 0, 1, -1};56int n, m, depth[4000][4000], ans = 1;7string snow[4000];89bool inside(int x, int y) {10 return (x > -1 && x < n && y > -1 && y < m && snow[x][y] != '.');
Problems
Status | Source | Problem Name | Difficulty | Tags | Solution | URL |
---|---|---|---|---|---|---|
CSES | Easy | Show TagsBFS | ||||
CSES | Easy | Show TagsBFS | View Solution | |||
CSES | Normal | Show TagsCycle | ||||
CSA | Normal | Show TagsBFS, DFS | Check CSA | |||
Silver | Easy | Show TagsBFS | External Sol | |||
Gold | Normal | Show TagsBFS | External Sol | |||
Gold | Normal | External Sol | ||||
Old Silver | Normal | Show TagsBFS | External Sol | |||
Gold | Hard | Show TagsBFS | ||||
Gold | Hard | Show TagsBFS | External Sol | |||
Gold | Very Hard | External Sol |
Module Progress:
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!