Breadth-First Search (BFS)

Computational complexity: O(V + E)

Unvisited
Current
In Queue
Visited
Enter start node and click "Start" to begin BFS

C

void bfs(int graph[][7], int start, int n) {
    int visited[7] = {0};
    int queue[7], front = 0, rear = 0;
    visited[start] = 1;
    queue[rear++] = start;
    while (front < rear) {
        int current = queue[front++];
        for (int i = 0; i < n; i++) {
            if (graph[current][i] && !visited[i]) {
                visited[i] = 1;
                queue[rear++] = i;
            }
        }
    }
}

C++

void bfs(vector<int> adj[], int start, int n) {
    vector<bool> visited(n, false);
    queue<int> q;
    visited[start] = true;
    q.push(start);
    while (!q.empty()) {
        int current = q.front();
        q.pop();
        for (int neighbor : adj[current]) {
            if (!visited[neighbor]) {
                visited[neighbor] = true;
                q.push(neighbor);
            }
        }
    }
}

Java

void bfs(ArrayList<Integer>[] adj, int start) {
    boolean[] visited = new boolean[adj.length];
    Queue<Integer> queue = new LinkedList<>();
    visited[start] = true;
    queue.add(start);
    while (!queue.isEmpty()) {
        int current = queue.poll();
        for (int neighbor : adj[current]) {
            if (!visited[neighbor]) {
                visited[neighbor] = true;
                queue.add(neighbor);
            }
        }
    }
}

Go

func bfs(adj map[int][]int, start int) {
    visited := make(map[int]bool)
    queue := []int{start}
    visited[start] = true
    for len(queue) > 0 {
        current := queue[0]
        queue = queue[1:]
        for _, neighbor := range adj[current] {
            if !visited[neighbor] {
                visited[neighbor] = true
                queue = append(queue, neighbor)
            }
        }
    }
}

PHP

function bfs(array $adj, int $start): void {
    $visited = array_fill(0, count($adj), false);
    $queue = [$start];
    $visited[$start] = true;
    while (!empty($queue)) {
        $current = array_shift($queue);
        foreach ($adj[$current] as $neighbor) {
            if (!$visited[$neighbor]) {
                $visited[$neighbor] = true;
                $queue[] = $neighbor;
            }
        }
    }
}

Perl

sub bfs {
    my ($adj, $start) = @_;
    my %visited;
    my @queue = ($start);
    $visited{$start} = 1;
    while (@queue) {
        my $current = shift @queue;
        foreach my $neighbor (@{$adj->{$current}}) {
            unless ($visited{$neighbor}) {
                $visited{$neighbor} = 1;
                push @queue, $neighbor;
            }
        }
    }
}

Python

from collections import deque

def bfs(adj, start):
    visited = set()
    queue = deque([start])
    visited.add(start)
    while queue:
        current = queue.popleft()
        for neighbor in adj[current]:
            if neighbor not in visited:
                visited.add(neighbor)
                queue.append(neighbor)

Ruby

def bfs(adj, start)
    visited = Set.new
    queue = [start]
    visited.add(start)
    while !queue.empty?
        current = queue.shift
        adj[current].each do |neighbor|
            unless visited.include?(neighbor)
                visited.add(neighbor)
                queue.push(neighbor)
            end
        end
    end
end

Delphi

procedure BFS(const Adj: array of array of Integer; Start: Integer);
var
    Visited: array of Boolean;
    Queue: array of Integer;
    Front, Rear, Current, I: Integer;
begin
    SetLength(Visited, Length(Adj));
    SetLength(Queue, Length(Adj));
    Front := 0;
    Rear := 0;
    Visited[Start] := True;
    Queue[Rear] := Start;
    Inc(Rear);
    while Front < Rear do
    begin
        Current := Queue[Front];
        Inc(Front);
        for I := 0 to High(Adj[Current]) do
            if (Adj[Current, I] > 0) and not Visited[I] then
            begin
                Visited[I] := True;
                Queue[Rear] := I;
                Inc(Rear);
            end;
    end;
end;

Rust

use std::collections::{HashSet, VecDeque};

fn bfs(adj: &HashMap<usize, Vec<usize>>, start: usize) {
    let mut visited: HashSet<usize> = HashSet::new();
    let mut queue: VecDeque<usize> = VecDeque::new();
    visited.insert(start);
    queue.push_back(start);
    while let Some(current) = queue.pop_front() {
        for &neighbor in adj.get(¤t).unwrap_or(&Vec::new()) {
            if visited.insert(neighbor) {
                queue.push_back(neighbor);
            }
        }
    }
}

Assembler

; BFS implementation with queue
section .bss
    visited resb 7
    queue resd 7
    front resd 1
    rear resd 1

section .text
bfs:
    mov byte [visited + eax], 1
    mov [queue], eax
    mov dword [front], 0
    mov dword [rear], 1
loop:
    mov ebx, [front]
    cmp ebx, [rear]
    jge done
    mov ecx, [queue + ebx*4]
    inc dword [front]
    ; Process neighbors...
    jmp loop
done:
    ret

JavaScript

function bfs(adj, start)
{
    const visited = new Set();
    const queue = [start];
    visited.add(start);
    while (queue.length > 0) {
        const current = queue.shift();
        for (const neighbor of adj[current]) {
            if (!visited.has(neighbor)) {
                visited.add(neighbor);
                queue.push(neighbor);
            }
        }
    }
}

Lua

function bfs(adj, start)
    local visited = {}
    local queue = {start}
    visited[start] = true
    while #queue > 0 do
        local current = table.remove(queue, 1)
        for _, neighbor in ipairs(adj[current]) do
            if not visited[neighbor] then
                visited[neighbor] = true
                table.insert(queue, neighbor)
            end
        end
    end
end