+/*
+ * Initialize breadth-first search.
+ */
+static void
+bfs_init(void)
+{
+ int i;
+
+ for (i = 0; i < WORLD_SZ(); i++) {
+ closest[i] = -1;
+ distance[i] = USHRT_MAX;
+ }
+
+ bfs_queue_head = bfs_queue_tail = 0;
+}
+
+/*
+ * Add sector @x,@y to the BFS queue.
+ * It's closest to @c, with distance @dist.
+ */
+static void
+bfs_enqueue(int c, int x, int y, int dist)
+{
+ int off = XYOFFSET(x, y);
+
+ assert(dist < distance[off]);
+ closest[off] = c;
+ distance[off] = dist;
+ bfs_queue[bfs_queue_tail] = off;
+ bfs_queue_tail++;
+ if (bfs_queue_tail >= WORLD_SZ())
+ bfs_queue_tail = 0;
+ assert(bfs_queue_tail != bfs_queue_head);
+}
+
+/*
+ * Search breadth-first until the queue is empty.
+ */
+static void
+bfs_run_queue(void)
+{
+ int off, dist, i, noff, nx, ny;
+ coord x, y;
+
+ while (bfs_queue_head != bfs_queue_tail) {
+ off = bfs_queue[bfs_queue_head];
+ bfs_queue_head++;
+ if (bfs_queue_head >= WORLD_SZ())
+ bfs_queue_head = 0;
+ dist = distance[off] + 1;
+ sctoff2xy(&x, &y, off);
+ for (i = DIR_FIRST; i <= DIR_LAST; i++) {
+ nx = new_x(x + diroff[i][0]);
+ ny = new_y(y + diroff[i][1]);
+ noff = XYOFFSET(nx, ny);
+ if (dist < distance[noff]) {
+ bfs_enqueue(closest[off], nx, ny, dist);
+ } else if (distance[noff] == dist) {
+ if (closest[off] != closest[noff])
+ closest[noff] = (natid)-1;
+ } else
+ assert(distance[noff] < dist);
+ }
+ }
+}
+
+/*
+ * Add island @c's coastal sectors to the BFS queue, with distance 0.
+ */
+static void
+bfs_enqueue_island(int c)
+{
+ int i;
+
+ for (i = 0; i < isecs[c]; i++) {
+ if (sectc[c][i])
+ bfs_enqueue(c, sectx[c][i], secty[c][i], 0);
+ }
+}
+
+/*
+ * Compute spheres of influence
+ * A continent's sphere of influence is the set of sectors closer to
+ * it than to any other continent.
+ * Set closest[XYOFFSET(x, y)] to the closest continent's number,
+ * -1 if no single continent is closest.
+ * Set distance[XYOFFSET(x, y)] to the distance to the closest coastal
+ * land sector.
+ */
+static void
+init_spheres_of_influence(void)
+{
+ int c;
+
+ bfs_init();
+ for (c = 0; c < nc; c++)
+ bfs_enqueue_island(c);
+ bfs_run_queue();
+}
+