intermediate · BFS · multi-source BFS · level order · grid

Minutes until the whole office knows

Problem

An open-plan office is a grid of desks: 0 is an empty desk, 1 a colleague who has not heard the news, 2 a colleague who knows it. Every minute, everyone who knows tells the colleagues directly above, below, left and right of them.

Return the number of minutes until nobody is left uninformed, 0 if nobody needed telling, or −1 if someone can never be reached. Grid input is row by row with its width (○ = not yet told, ● = knows).

Constraints

  • 1 ≤ cells ≤ 30, width 1 to 8 (visualization limit)
  • cells are 0, 1 or 2

Examples

office = [[2, 1, 1], [1, 1, 0], [0, 1, 1]] → 4

office = [[2, 0, 1]] → -1 — The empty desk blocks the only route.

Show the solution

Multi-source BFS by levels

All informers start together, so they are all level 0 of one BFS. Level m is exactly the set of colleagues told in minute m.

Why it is correct

Invariant: at the start of minute m, the queue holds exactly the colleagues who learned the news in minute m − 1 (level m − 1 of a BFS from all sources at once). Each of them tells its uninformed neighbours, which are therefore told in minute m and form the next level. BFS reaches every colleague connected to some source, at their smallest distance to any source, so the number of levels needed is the largest such distance. Anyone still uninformed when the queue empties is not connected to a source: −1.

Complexity

Time O(rows · columns), extra space O(rows · columns). Each cell is enqueued at most once (when it turns to 2) and checks its 4 neighbours once.

For contrast: Simulate: each minute, build the next grid from the current one, until nothing changes. That costs O((rows · columns)²) time and O(rows · columns) space.

Edge cases

  • Nobody uninformed: 0 minutes.
  • Uninformed colleagues but no informer: −1.
  • Several informers spreading towards each other.

Common mistakes

  • Running a separate BFS from each informer and adding times.
  • Counting a minute for the last level, which told nobody.

Step through it

The solution in four languages

Each is checked against one shared set of cases and a randomized comparison with a brute-force reference.

namespace Bekadan.Dsa.Examples.Problems;
 
public static class SpreadTime
{
    private static readonly (int Dr, int Dc)[] Moves = [(-1, 0), (1, 0), (0, -1), (0, 1)];
 
    /// <summary>0 empty, 1 not told, 2 knows. Minutes until nobody is untold (each minute spreads to 4 neighbours), or -1. Multi-source BFS.</summary>
    public static int Minutes(int[][] grid)
    {
        int rows = grid.Length, cols = grid[0].Length;
        var state = grid.Select(row => (int[])row.Clone()).ToArray();
        var queue = new Queue<(int R, int C)>();
        int unaware = 0;
        for (int r = 0; r < rows; r++)
        {
            for (int c = 0; c < cols; c++)
            {
                if (state[r][c] == 2) queue.Enqueue((r, c));
                else if (state[r][c] == 1) unaware++;
            }
        }
        int minutes = 0;
        while (queue.Count > 0 && unaware > 0)
        {
            minutes++;
            for (int size = queue.Count; size > 0; size--) // exactly those told in the previous minute
            {
                var (r, c) = queue.Dequeue();
                foreach (var (dr, dc) in Moves)
                {
                    int nr = r + dr, nc = c + dc;
                    if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && state[nr][nc] == 1)
                    {
                        state[nr][nc] = 2;
                        unaware--;
                        queue.Enqueue((nr, nc));
                    }
                }
            }
        }
        return unaware == 0 ? minutes : -1;
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Problems/SpreadTime.cs

from collections import deque
from collections.abc import Sequence
 
MOVES = ((-1, 0), (1, 0), (0, -1), (0, 1))
 
 
def minutes(grid: Sequence[Sequence[int]]) -> int:
    """0 empty, 1 not told, 2 knows. Minutes until nobody is untold (spreading to 4 neighbours per minute), or -1."""
    rows, cols = len(grid), len(grid[0])
    state = [list(row) for row in grid]
    queue = deque((r, c) for r in range(rows) for c in range(cols) if state[r][c] == 2)
    unaware = sum(row.count(1) for row in state)
    elapsed = 0
    while queue and unaware > 0:
        elapsed += 1
        for _ in range(len(queue)):  # exactly those told in the previous minute
            r, c = queue.popleft()
            for dr, dc in MOVES:
                nr, nc = r + dr, c + dc
                if 0 <= nr < rows and 0 <= nc < cols and state[nr][nc] == 1:
                    state[nr][nc] = 2
                    unaware -= 1
                    queue.append((nr, nc))
    return elapsed if unaware == 0 else -1

Tested on CPython 3.14.0 · examples/python/dsa_examples/problems/spread_time.py

package dev.bekadan.dsa.problems;
 
import java.util.ArrayDeque;
import java.util.Deque;
 
public final class SpreadTime {
    private SpreadTime() {
    }
 
    private static final int[][] MOVES = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
 
    /** 0 empty, 1 not told, 2 knows. Minutes until nobody is untold (spreading to 4 neighbours per minute), or -1. */
    public static int minutes(int[][] grid) {
        int rows = grid.length;
        int cols = grid[0].length;
        int[][] state = new int[rows][];
        for (int r = 0; r < rows; r++) {
            state[r] = grid[r].clone();
        }
        Deque<int[]> queue = new ArrayDeque<>();
        int unaware = 0;
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < cols; c++) {
                if (state[r][c] == 2) {
                    queue.add(new int[] {r, c});
                } else if (state[r][c] == 1) {
                    unaware++;
                }
            }
        }
        int minutes = 0;
        while (!queue.isEmpty() && unaware > 0) {
            minutes++;
            for (int size = queue.size(); size > 0; size--) { // exactly those told in the previous minute
                int[] cell = queue.poll();
                for (int[] m : MOVES) {
                    int nr = cell[0] + m[0];
                    int nc = cell[1] + m[1];
                    if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && state[nr][nc] == 1) {
                        state[nr][nc] = 2;
                        unaware--;
                        queue.add(new int[] {nr, nc});
                    }
                }
            }
        }
        return unaware == 0 ? minutes : -1;
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/problems/SpreadTime.java

#pragma once
 
#include <array>
#include <cstddef>
#include <queue>
#include <utility>
#include <vector>
 
namespace bekadan::dsa::problems {
 
namespace spread_time_detail {
inline constexpr std::array<std::array<int, 2>, 4> kMoves{{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}};
}  // namespace spread_time_detail
 
// 0 empty, 1 not told, 2 knows. Minutes until nobody is untold (spreading to 4 neighbours per minute), or -1.
inline int spread_time(const std::vector<std::vector<int>>& grid) {
    const int rows = static_cast<int>(grid.size()), cols = static_cast<int>(grid[0].size());
    auto state = grid;
    const auto at = [&](int r, int c) -> int& { return state[static_cast<std::size_t>(r)][static_cast<std::size_t>(c)]; };
    std::queue<std::pair<int, int>> queue;
    int unaware = 0;
    for (int r = 0; r < rows; ++r) {
        for (int c = 0; c < cols; ++c) {
            if (at(r, c) == 2) queue.emplace(r, c);
            else if (at(r, c) == 1) ++unaware;
        }
    }
    int minutes = 0;
    while (!queue.empty() && unaware > 0) {
        ++minutes;
        for (auto size = queue.size(); size > 0; --size) {  // exactly those told in the previous minute
            const auto [r, c] = queue.front();
            queue.pop();
            for (const auto& [dr, dc] : spread_time_detail::kMoves) {
                const int nr = r + dr, nc = c + dc;
                if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && at(nr, nc) == 1) {
                    at(nr, nc) = 2;
                    --unaware;
                    queue.emplace(nr, nc);
                }
            }
        }
    }
    return unaware == 0 ? minutes : -1;
}
 
}  // namespace bekadan::dsa::problems

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/problems/spread_time.hpp