3D Space Exploration
InterviewTime limit1sMemory limit128 MB
Count connected groups of '*' blocks in an N x N x N grid, where blocks connect only across shared faces.
- Level
Easy3 of 10
- Topics
- Graph, DFS, BFS, Implementation
- Solved
- No attempts yet
Problem
Farmer John's cows have finally blasted off from Earth and are now drifting through space in their Moocraft. To reach their kin on Io, a moon of Jupiter, they must first cross a dangerous asteroid belt.
Bessie is piloting the craft through an () sector of space. Every asteroid in the sector is a group of blocks of space-rock joined face to face. Two blocks that touch only along an edge, or only at a single corner, belong to different asteroids.
Count the number of distinct asteroids in the sector.
The sector is given as square slices stacked one behind another (front to back). Each slice is an grid in which * marks a block of space-rock and . marks empty space. A block at slice , row , column shares a face with the blocks at , , and , and blocks joined this way belong to the same asteroid.
For example, consider a sector. Here M marks the Moocraft's start at and D marks the destination at ; these markers only help orient the map and are not needed to solve the problem.
Close slice Middle slice Far Slice Assembled with overlaps
+---+ +---+ +---+ +---+ Far
|M..| |..*| |...| |...|
|.*.| |.*.| |.*.| +---+.|
|...| |*..| |..D| |..*|D|
+---+ +---+ +---+ +---+.|-+
|M..|.|
|.*.|-+
|...|
Close +---+
Visual inspection shows three asteroids, including a long one running straight through the middle of the sector. The next figure labels each block with the number of the asteroid it belongs to:
+---+ Far
/|...|
/ |.1.|
/ |...|
/ +---+
+---+ /
/|..3| /
/ |.1.| /
/ |2..|/
/ +---+
+---+ /
|...| /
|.1.| /
|...|/
Close +---+
Input
- The first line contains a single integer ().
- The next lines describe the slices in order. Each slice is given as lines of exactly characters, where each character is
*(a block of space-rock) or.(empty space). - Counting after the first line, lines through (for ) form slice . Within a slice the lines are its rows and the characters within a line are its columns, so the same row and column of two adjacent slices are aligned and share a face.
Output
- Print a single integer: the number of distinct asteroids in the sector.