public static void floodSearch(Set<PS> set, Faction color, int max) { // Clean if (set == null) throw new NullPointerException("set"); if (color == null) throw new NullPointerException("color"); // Expand Set<PS> expansion = new LinkedHashSet<PS>(); for (PS chunk : set) { Set<PS> neighbours = MUtil.set( chunk.withChunkX(chunk.getChunkX() + 1), chunk.withChunkX(chunk.getChunkX() - 1), chunk.withChunkZ(chunk.getChunkZ() + 1), chunk.withChunkZ(chunk.getChunkZ() - 1)); for (PS neighbour : neighbours) { if (set.contains(neighbour)) continue; Faction faction = BoardColl.get().getFactionAt(neighbour); if (faction == null) continue; if (faction != color) continue; expansion.add(neighbour); } } set.addAll(expansion); // No Expansion? if (expansion.isEmpty()) return; // Reached Max? if (set.size() >= max) return; // Recurse floodSearch(set, color, max); }