Efficiently Detecting Enclosed Spaces in a Browser Game

2025-02-07
Efficiently Detecting Enclosed Spaces in a Browser Game

In a browser game, players place obstacles to hinder enemies. To prevent players from cheating by enclosing themselves or enemies, the author designed an efficient algorithm to detect enclosed spaces. The initial brute-force approach—flood filling from every cell—proved too slow. The author devised an improved algorithm that leverages a cache of "open-faced" cells (cells not surrounded by obstacles) to prune the flood fill search space. When obstacles are added or removed, the algorithm updates the open-faced cell set and recalculates legal placement locations. While the worst-case time complexity remains the same as brute-force flood fill, in practice, this algorithm significantly reduces lag. The author also discusses other optimization tricks, such as iterative updates and checking only cells adjacent to multiple obstacles. Finally, the author mentions another possible solution: a cycle detection-based algorithm.