THINK FIRST·CODE LATER

← All labs

Shortest way out of a maze with BFS

Problem

Write MazeBfs. Read rows cols and a maze: # wall, . free cell, S start, E exit. Moves go up, down, left or right. A grid is a graph whose vertices are the free cells, so run breadth-first search from S, storing in distance[r][c] the number of steps of the first visit (−1 = not reached).

Print the length of the shortest way out (or No way out), the number of cells reachable from S (S included) and the distance of the farthest reachable cell.

For the input

5 7
S.#....
.##.##.
....#E.
.##.#..
...#...

the program prints

Shortest way out: 13 steps
Cells reachable from S: 25
Farthest reachable cell: 16 steps away

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.

d15-6-data-1.txt

5 7
S.#....
.##.##.
....#E.
.##.#..
...#...
What your program must print for d15-6-data-1.txt
Shortest way out: 13 steps
Cells reachable from S: 25
Farthest reachable cell: 16 steps away

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 < d15-6-data-1.txt

Windows PowerShell does not understand <:

Get-Content d15-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.