problems / 209

Suki's Quick Treat Fetch

easy bfs graphs shortest-paths 1000 ms · 256 MB

Suki's Quick Treat Fetch

Suki is a black, curly-coated dog with a grey beard and white paws. She's spotted a delicious pink treat in one corner of a rectangular room, and she wants to reach it as quickly as possible. However, the room contains some furniture and obstacles that block her path. She can only walk through open floor space, moving one cell at a time in any of the four cardinal directions (up, down, left, right).

Given a grid representation of the room, find the shortest distance (minimum number of steps) for Suki to reach the treat from her starting position.

Input

The first line contains two integers R and C (1 ≤ R, C ≤ 100): the dimensions of the room.

The next R lines each contain C characters representing the room:

  • S marks Suki's starting position (exactly one).
  • T marks the treat's position (exactly one).
  • . marks an open floor cell.
  • # marks an obstacle (wall or furniture).

Output

Print a single integer: the minimum number of steps Suki needs to reach the treat. If the treat is unreachable, print -1.

Notes

Suki can only move through cells marked with . or her starting position S. The treat may be on any cell including T. The shortest path is found using breadth-first search.

Example 1

Input

4 4
S...
....
....
...T

Output

6

Example 2

Input

3 3
S.T
###
...

Output

2

Hints · reveal one at a time if you're stuck

Hint 1

Walls and furniture can force a detour, so a straight-line distance is not enough. Which search explores the cells in order of how many steps they are from S?

Hint 2

Search outward from S, one step at a time, marking each cell when you first reach it so it is handled only once. Stop when you reach T, or report -1 if the search runs out of cells.

report an issue Prefer your own editor? sooks prep 209 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.