THINK FIRST·CODE LATER

← All labs

Counting islands with a recursive flood fill

Problem

A satellite map is a grid of land (#) and water (.). An island is a group of land cells connected horizontally or vertically. Write Islands: read rows cols and the rows of the map, then scan the grid row by row; each time you meet an unvisited land cell, a recursive method flood(r, c) must visit the whole island (down, up, right, left), mark its cells as visited by turning them into water, and return its size.

Print the number of land cells, the number of islands, their sizes in order of discovery and the largest size.

For the input

4 6
##..#.
#...#.
..#...
.###.#

the program prints

Land cells: 10
Islands: 4
Sizes in order of discovery: 3 2 4 1
Largest island: 4

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

d1-6-data-1.txt

4 6
##..#.
#...#.
..#...
.###.#
What your program must print for d1-6-data-1.txt
Land cells: 10
Islands: 4
Sizes in order of discovery: 3 2 4 1
Largest island: 4

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < d1-6-data-1.txt

Windows PowerShell does not understand <:

Get-Content d1-6-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.