Algorithm Search⌘K

Algorithmcore

Frontier-based exploration

Also called frontier exploration.

Yamauchi's method that moves the robot to the nearest boundary between known free space and unknown space, until no frontier is left.

Time
O(c^2 r^2) worst
Space
O(c) extra
Where
c = the number of grid cells; r = the sensor range in cells
Properties
deterministicnot exactonlinenot randomized
Origin
Brian Yamauchi, 1997

Frontier-based exploration lets a mobile robot build a map of an unknown place on its own. The robot keeps an occupancy grid in which each cell is unknown, free or occupied. A frontier is the boundary between the known free space and the unknown space: a free cell next to an unknown cell. Brian Yamauchi's rule is simple. Find the frontiers, group the adjacent frontier cells into regions, drive to the nearest region that the robot can reach through known free space, and look around there. Each visit pushes the boundary of the known map outward. When no reachable frontier is left, the part of the world that the robot can reach is mapped. The method needs no model of the environment and works with any sensor that can mark cells as free or occupied, which is why it is still the default baseline for exploration.

In plain words

Imagine walking into a dark building with a flashlight. You see a little of each room. Wherever the lit floor ends and darkness begins, there is something left to see. So you walk to the nearest such edge, shine the light, and look again. Each time, the dark part shrinks. You stop when every edge between lit floor and darkness is behind a wall or out of reach. Then you have seen every place you could walk to.

The method does not plan the best tour. It only goes to the closest edge each time, so it can walk back and forth more than needed. But it is simple and it always finishes.

The problem

Input. A grid world of cc cells, each free or occupied, that the robot does not know; a start cell, which is free; and a sensor of range rr cells. At each cell, the sensor casts digital lines from the robot to every cell on the square of radius rr around it, and reveals the cells along each line up to and including the first occupied one. The robot moves between free cells that share a side, and only through cells its map marks free. Cells are integers and each map access costs one step, as in the word RAM.

Output. A map in which every free cell that the robot can reach from the start is marked free, and the walk that produced it.

How it differs from close pages. Coverage path planning assumes a known map and asks for a path that passes over every point; exploration asks only to see every point, in a map that is built along the way. Next-best-view planning scores candidate views by the unknown volume they would reveal and picks the best; frontier exploration picks the nearest frontier, which is cheaper and needs no sensor model beyond free, occupied and unknown. Building the map itself, with noisy poses, is the SLAM problem.

The algorithm

  1. EXPLORE(start)
  2. 1mark every cell unknown, then the start free; p ← start; SENSE(p)
  3. 2loop: F ← the free cells with an unknown neighbor
  4. 3group F into 8-connected regions and keep the regions with at least min_size cells
  5. 4P ← a shortest path, through free cells, from p to the nearest cell of a kept region
  6. 5if there is no such path then return the map
  7. 6for each cell q of P after p:
  8. 7p ← q; SENSE(p)

Line L2 finds the frontier cells; the code tests the four neighbors that share a side. Line L3 finds the connected components of the frontier cells, with diagonal cells counted as adjacent, and drops small regions, which Yamauchi did to ignore frontiers smaller than the robot. Line L4 is a breadth-first search from the robot over the free cells, which stops at the first frontier cell of a kept region. The robot senses at every cell on the way (line L7), so the map often changes before it arrives; the code still finishes the path, then plans again.

Example

A building of 10×510 \times 5 cells has two rooms joined by a doorway in the bottom row (# is a wall):

##########
#....#...#
#....#...#
#........#
##########

The robot starts in the top left corner of the left room, at column 1 and row 1, with a sensor range of 2 cells. It sees part of the left room, and the frontier is one region along the right and bottom of what it saw. Then:

Plan Path What it sees on arrival
1 (1,1) to (3,1) the rest of the left room and the wall at column 5
2 (3,1) to (3,3) the bottom wall of the left room
3 (3,3) to (5,3) through the doorway into the right room, up to column 7
4 (5,3) to (7,3) the bottom and right of the right room
5 (7,3) to (7,1) the top wall of the right room

After 5 plans and 10 moves, no free cell has an unknown neighbor. The corner cell outside the walls at (0,4) stays unknown, since no ray reaches it and it has no free neighbor.

Correctness

The proof shows two facts, for a sensor that marks cells correctly and has range at least 1, and for min_size = 1. First, the method stops: each plan ends at a cell that had an unknown neighbor, and the sensing at that cell reveals the neighbor, so the number of unknown cells drops with every plan, and there are at most cc plans. Second, when it stops, every free cell that the robot can reach from the start is marked free: otherwise, on a path through free cells to an unknown one, the last known cell before the first unknown cell is a frontier that line L4 reaches. With min_size > 1, the method still stops, but it can stop early and leave small regions unexplored. The tests check the frontier cells, the regions and the shortest paths against their definitions, and check both facts on 25 random worlds with random sensor ranges.

Proof: Frontier exploration stops and maps every reachable free cellfull

Line numbers refer to the pseudocode on the frontier-based exploration page. The world is a finite grid of cc cells, each free or occupied. Two cells are neighbors when they share a side. The robot's map gives each cell one of the states unknown, free and occupied.

Assumptions. (A1) The sensor is correct: it marks a cell free only if it is free, and occupied only if it is occupied, and it never changes a known cell. (A2) The sensor range is r≥1r \ge 1, so sensing at a cell reveals each of its neighbors: the neighbor is the first cell of the digital line toward the middle of one side of the square of radius rr. (A3) The start cell is free, and min_size = 1, so line L3 keeps every frontier cell.

Let RR be the set of free cells that can be reached from the start by moves between free neighbors.

Lemma 1 (the map stays correct and the robot stays safe). At every moment, every cell marked free is free, every cell marked occupied is occupied, and the robot stands on a cell marked free.

Proof. Line L1 marks the start free, which is correct by (A3), and every other change of the map comes from the sensor, which is correct by (A1). The robot moves only along a path found by line L4, whose cells are marked free. □\square

Lemma 2 (each plan removes an unknown cell). Let uku_k be the number of unknown cells when line L4 runs for the kk-th time. If plan kk finds a path, then uk+1<uku_{k+1} < u_k.

Proof. After sensing at the robot's cell, all its neighbors are known by (A2). So the robot's cell is never a frontier cell when line L4 runs, and the path PP has at least two cells. Its last cell tt was a frontier cell when the plan was made, so tt had an unknown neighbor vv. Line L7 senses at tt, which reveals vv by (A2). Known cells never become unknown, so uk+1≤uk−1u_{k+1} \le u_k - 1. □\square

Theorem. The method stops after at most cc plans, and when it stops, every cell of RR is marked free.

Proof. The number of unknown cells is between 0 and cc, and by Lemma 2 it drops with every plan that finds a path. So after at most cc such plans, line L5 returns.

Suppose that when it returns, some cell of RR is not marked free. By Lemma 1, a cell of RR is never marked occupied, so that cell is unknown. Take a path s=q0,q1,…,qms = q_0, q_1, \dots, q_m of free neighbors from the start ss to that cell, and let qjq_j be the first unknown cell on it; j≥1j \ge 1, since the start is marked free. The cells q0,…,qj−1q_0, \dots, q_{j-1} are known, and they are free, so by Lemma 1 they are marked free. Then qj−1q_{j-1} is a frontier cell: it is marked free and has the unknown neighbor qjq_j. The robot stands on some cell marked free; to show that line L4 reaches qj−1q_{j-1}, it is enough that the robot's cell and ss are joined through cells marked free. Every path the robot took ran through cells marked free, and cells marked free stay marked free, so the robot's whole trail from ss is still a chain of cells marked free. Followed by q0,…,qj−1q_0, \dots, q_{j-1}, it joins the robot to qj−1q_{j-1} through cells marked free. So the breadth-first search of line L4 finds a path to a frontier cell, and line L5 does not return. This contradiction proves the claim. □\square

Remarks. Only (A3) uses min_size = 1. With a larger minimum, Lemma 2 still holds, so the method still stops after at most cc plans, but a small frontier region can be dropped, and the second claim fails; the test test_a_large_minimum_size_stops_at_once shows the extreme case. With a noisy sensor, (A1) fails, and a cell of RR marked occupied by mistake can hide part of the world. The number of plans can be close to cc: with r=1r = 1 in a corridor of LL cells, the robot plans L−2L - 2 times, which test_corridor_by_hand checks for L=10L = 10. The test test_explores_every_reachable_cell checks Lemma 1 and the theorem on 25 random worlds.

Complexity

  • Time. Each plan costs O(c)O(c) for lines L2 to L4, and there are at most cc plans. Each path has at most cc cells, and each sensing casts 8r8r lines of at most r+1r + 1 cells. This gives O(c2r2)O(c^2 r^2) in the worst case. In practice, paths are short. Measured on 40×4040 \times 40 worlds with 20% random obstacles: with r=4r = 4, about 80 plans, 410 moves and 0.2 s in this Python code; with r=8r = 8, about 47 plans and 320 moves.
  • Space. O(c)O(c) for the map, the frontier set and the search.

Properties

  • Complete for reachable space. With a correct sensor and no minimum size, every free cell reachable from the start ends up known.
  • Not optimal. Going to the nearest frontier is a greedy choice. The length of the walk has no constant-factor bound against the shortest walk that sees everything; this would be a watchman route problem on a map that the robot does not have.
  • Model-free. It needs only the three states of each cell, not a probabilistic sensor model.
  • Online and replanning. Each plan uses the current map only, so new obstacles and new openings are handled at the next plan.

Variants and improvements

  • Scored frontiers. Weigh the distance to a frontier against the expected information gain at it, as in next-best-view planning.
  • Multiple robots. Each robot goes to a different frontier, assigned by distance, by an auction, or by a task allocation method, and the robots share one map.
  • Fast frontier detection. Instead of scanning the whole grid, update the frontier set only in the cells that the last scan changed.
  • 3D exploration. The same idea runs on an octree map of voxels for aerial robots, often with a frontier region scored by its size.
  • Exploration with SLAM. When the pose is uncertain, the planner can also pick goals that revisit known places to close loops.

When to use it

Use frontier-based exploration when a robot must map an unknown indoor space by itself and the map is a grid. It is a strong baseline, easy to add on top of any grid mapping system. When travel is expensive, as for an aerial robot with a short battery life, or the sensor sees far, a method that scores views by information gain usually maps the same space with a shorter path.

Pitfalls

  • Noisy maps. A sensor that leaves holes in known free space creates many tiny frontiers. A minimum region size, or a filter on the map, removes them, but too large a size stops the exploration early: in our measurements on 20×2020 \times 20 worlds with r=2r = 2, a minimum size of 3 sometimes stopped before the first move.
  • Unreachable frontiers. A frontier seen through a gap that the robot cannot pass keeps the robot trying. Plan only to frontiers that the path search can reach, as line L4 does, and blacklist goals that fail.
  • Oscillation. If two frontiers are almost equally near, the nearest one can change at every plan. Commit to a goal until it is reached or is no longer a frontier.
  • Pose drift. The method assumes the map is correct. With drift, frontiers appear in the wrong place; use a SLAM system underneath.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

frontier_based_exploration.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/frontier-based-exploration/. The authors are listed in prov/KCQHFD.jsonl.

"""Frontier-based exploration (Yamauchi 1997) on a grid.

The true world is a list of strings: '#' is an obstacle, anything else is free. The robot
knows nothing at the start. Its map has three states per cell: UNKNOWN, FREE and OCC.
The sensor casts Bresenham rays from the robot cell to every cell on the square of
Chebyshev radius r; along each ray it marks cells FREE until it meets an obstacle, which
it marks OCC. The robot moves one cell at a time between 4-neighbors, only on cells its
map marks FREE.

A frontier cell is a FREE cell with an UNKNOWN 4-neighbor. The method groups frontier
cells into 8-connected regions, keeps the regions with at least min_size cells, and drives
to the nearest cell of a kept region (by breadth-first search over FREE cells), sensing
at each cell of the path. It stops when no kept region is reachable.
"""

from collections import deque

UNKNOWN, FREE, OCC = -1, 0, 1
STEPS4 = ((1, 0), (-1, 0), (0, 1), (0, -1))
STEPS8 = STEPS4 + ((1, 1), (1, -1), (-1, 1), (-1, -1))


def bresenham(x0, y0, x1, y1):
    """The cells of the digital line from (x0, y0) to (x1, y1), both ends included."""
    dx, dy = abs(x1 - x0), -abs(y1 - y0)
    sx, sy = (1 if x1 > x0 else -1), (1 if y1 > y0 else -1)
    err = dx + dy
    out = []
    while True:
        out.append((x0, y0))
        if x0 == x1 and y0 == y1:
            return out
        e2 = 2 * err
        if e2 >= dy:
            err += dy
            x0 += sx
        if e2 <= dx:
            err += dx
            y0 += sy


def sense(world, known, x, y, r):
    """Cast rays to the square of radius r around (x, y). Returns the number of new cells."""
    rows, cols = len(world), len(world[0])
    new = 0
    ring = [(x + i, y - r) for i in range(-r, r + 1)] + [(x + i, y + r) for i in range(-r, r + 1)]
    ring += [(x - r, y + j) for j in range(-r + 1, r)] + [(x + r, y + j) for j in range(-r + 1, r)]
    for tx, ty in ring:
        for cx, cy in bresenham(x, y, tx, ty)[1:]:
            if not (0 <= cx < cols and 0 <= cy < rows):
                break
            hit = world[cy][cx] == "#"
            if known[cy][cx] == UNKNOWN:
                known[cy][cx] = OCC if hit else FREE
                new += 1
            if hit:
                break
    return new


def frontier_cells(known):
    """FREE cells with at least one UNKNOWN 4-neighbor."""
    rows, cols = len(known), len(known[0])
    out = set()
    for y in range(rows):
        for x in range(cols):
            if known[y][x] != FREE:
                continue
            for dx, dy in STEPS4:
                nx, ny = x + dx, y + dy
                if 0 <= nx < cols and 0 <= ny < rows and known[ny][nx] == UNKNOWN:
                    out.add((x, y))
                    break
    return out


def frontier_regions(cells):
    """The 8-connected components of a set of cells, as a dict from cell to region id."""
    region = {}
    rid = 0
    for c in sorted(cells):
        if c in region:
            continue
        region[c] = rid
        stack = [c]
        while stack:
            x, y = stack.pop()
            for dx, dy in STEPS8:
                d = (x + dx, y + dy)
                if d in cells and d not in region:
                    region[d] = rid
                    stack.append(d)
        rid += 1
    return region


def nearest_frontier(known, start, targets):
    """Breadth-first search over FREE cells; returns the path to the nearest target, or None."""
    rows, cols = len(known), len(known[0])
    parent = {start: None}
    queue = deque([start])
    while queue:
        c = queue.popleft()
        if c in targets:
            path = []
            while c is not None:
                path.append(c)
                c = parent[c]
            return path[::-1]
        x, y = c
        for dx, dy in STEPS4:
            nx, ny = x + dx, y + dy
            if 0 <= nx < cols and 0 <= ny < rows and known[ny][nx] == FREE and (nx, ny) not in parent:
                parent[(nx, ny)] = c
                queue.append((nx, ny))
    return None


def explore(world, start, r=3, min_size=1, max_moves=100000):
    """Explore from start. Returns (known map, list of visited cells, number of plans)."""
    rows, cols = len(world), len(world[0])
    known = [[UNKNOWN] * cols for _ in range(rows)]  # @line L1
    x, y = start
    known[y][x] = FREE
    sense(world, known, x, y, r)  # @line L1
    trail, plans = [start], 0
    while len(trail) <= max_moves:
        cells = frontier_cells(known)  # @line L2
        region = frontier_regions(cells)  # @line L3
        size = {}
        for rid in region.values():
            size[rid] = size.get(rid, 0) + 1
        targets = {c for c in cells if size[region[c]] >= min_size}  # @line L3
        path = nearest_frontier(known, (x, y), targets)  # @line L4
        if path is None:  # @line L5
            return known, trail, plans
        plans += 1
        for cx, cy in path[1:]:  # @line L6
            x, y = cx, cy
            trail.append((x, y))
            sense(world, known, x, y, r)  # @line L7
    raise RuntimeError("move limit reached")
test_frontier_based_exploration.py 153 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/frontier-based-exploration/. The authors are listed in prov/KCQHFD.jsonl.

import random
from collections import deque

from frontier_based_exploration import (
    FREE,
    UNKNOWN,
    bresenham,
    explore,
    frontier_cells,
    frontier_regions,
    nearest_frontier,
)


def random_world(rng, rows, cols, density):
    return ["".join("#" if rng.random() < density else "." for _ in range(cols)) for _ in range(rows)]


def reachable(world, start):
    rows, cols = len(world), len(world[0])
    seen = {start}
    queue = deque([start])
    while queue:
        x, y = queue.popleft()
        for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
            nx, ny = x + dx, y + dy
            if 0 <= nx < cols and 0 <= ny < rows and world[ny][nx] != "#" and (nx, ny) not in seen:
                seen.add((nx, ny))
                queue.append((nx, ny))
    return seen


def test_bresenham_lines():
    rng = random.Random(31)
    for _ in range(300):
        x0, y0, x1, y1 = (rng.randint(-9, 9) for _ in range(4))
        line = bresenham(x0, y0, x1, y1)
        assert line[0] == (x0, y0) and line[-1] == (x1, y1)
        assert len(line) == max(abs(x1 - x0), abs(y1 - y0)) + 1
        for (ax, ay), (bx, by) in zip(line, line[1:]):
            assert max(abs(ax - bx), abs(ay - by)) == 1
        # Every cell is within half a cell of the true segment along the minor axis.
        dx, dy = x1 - x0, y1 - y0
        for cx, cy in line:
            if abs(dx) >= abs(dy) and dx != 0:
                assert abs((cy - y0) - dy * (cx - x0) / dx) <= 0.5 + 1e-12
            elif dy != 0:
                assert abs((cx - x0) - dx * (cy - y0) / dy) <= 0.5 + 1e-12


def random_known(rng, rows, cols):
    return [[rng.choice([UNKNOWN, FREE, FREE, 1]) for _ in range(cols)] for _ in range(rows)]


def test_frontier_cells_and_regions_match_definitions():
    rng = random.Random(32)
    for _ in range(40):
        known = random_known(rng, 9, 11)
        # A frontier cell is a FREE 4-neighbor of an UNKNOWN cell.
        expect = set()
        for y in range(9):
            for x in range(11):
                if known[y][x] == UNKNOWN:
                    for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                        nx, ny = x + dx, y + dy
                        if 0 <= nx < 11 and 0 <= ny < 9 and known[ny][nx] == FREE:
                            expect.add((nx, ny))
        cells = frontier_cells(known)
        assert cells == expect
        # Regions: two cells share a region exactly when a chain of 8-neighbors joins them.
        region = frontier_regions(cells)
        label = {c: c for c in cells}

        def find(c):
            while label[c] != c:
                c = label[c]
            return c

        for a in cells:
            for b in cells:
                if max(abs(a[0] - b[0]), abs(a[1] - b[1])) == 1:
                    label[find(a)] = find(b)
        for a in cells:
            for b in cells:
                assert (region[a] == region[b]) == (find(a) == find(b))


def test_nearest_frontier_is_a_shortest_path():
    rng = random.Random(33)
    for _ in range(40):
        known = random_known(rng, 8, 8)
        free = [(x, y) for y in range(8) for x in range(8) if known[y][x] == FREE]
        if len(free) < 3:
            continue
        start = rng.choice(free)
        targets = set(rng.sample(free, 2)) - {start}
        # Distances by repeated relaxation over FREE cells.
        dist = {c: (0 if c == start else 10 ** 9) for c in free}
        for _ in range(len(free)):
            for (x, y) in free:
                for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                    n = (x + dx, y + dy)
                    if n in dist:
                        dist[n] = min(dist[n], dist[(x, y)] + 1)
        best = min(dist[t] for t in targets)
        path = nearest_frontier(known, start, targets)
        if best >= 10 ** 9:
            assert path is None
            continue
        assert len(path) - 1 == best and path[-1] in targets and path[0] == start
        for (ax, ay), (bx, by) in zip(path, path[1:]):
            assert abs(ax - bx) + abs(ay - by) == 1 and known[by][bx] == FREE


def test_corridor_by_hand():
    world = ["." * 10]
    known, trail, plans = explore(world, (0, 0), r=1)
    assert plans == 8 and len(trail) == 9 and all(v == FREE for v in known[0])
    known, trail, plans = explore(world, (0, 0), r=3)
    assert plans == 2 and trail[-1] == (6, 0) and all(v == FREE for v in known[0])


def test_explores_every_reachable_cell():
    rng = random.Random(34)
    for trial in range(25):
        rows, cols = rng.randint(6, 16), rng.randint(6, 16)
        world = random_world(rng, rows, cols, 0.3)
        free = [(x, y) for y in range(rows) for x in range(cols) if world[y][x] != "#"]
        if not free:
            continue
        start = rng.choice(free)
        known, trail, plans = explore(world, start, r=rng.randint(1, 4))
        for y in range(rows):
            for x in range(cols):
                if known[y][x] != UNKNOWN:
                    assert (known[y][x] == FREE) == (world[y][x] != "#")
        for x, y in reachable(world, start):
            assert known[y][x] == FREE
        for (ax, ay), (bx, by) in zip(trail, trail[1:]):
            assert abs(ax - bx) + abs(ay - by) == 1 and world[by][bx] != "#"
        assert plans <= rows * cols
        assert not any(known[y][x] == FREE for x, y in frontier_cells(known)
                       if (x, y) in reachable(world, start))


def test_a_large_minimum_size_stops_at_once():
    world = ["." * 12 for _ in range(12)]
    known, trail, plans = explore(world, (5, 5), r=2, min_size=10 ** 6)
    assert plans == 0 and trail == [(5, 5)]
    assert sum(v != UNKNOWN for row in known for v in row) == 25

History

Yamauchi presented frontier-based exploration in 1997, at the IEEE International Symposium on Computational Intelligence in Robotics and Automation. His robot built an evidence grid from its range sensors, detected frontier cells, grouped them into regions, ignored regions smaller than the robot, and drove to the nearest accessible one. Yamauchi and others soon extended the idea to teams of robots that share one map. Frontiers became the basis of most later grid and voxel exploration systems.

References

  1. A frontier-based approach for autonomous exploration, pp. 146-151, the whole paper (frontier cells, frontier regions with a minimum size, and travel to the nearest accessible frontier)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example