#K55452. Minimum Steps to Collect All Flowers

    ID: 29978 Type: Default 1000ms 256MiB

Minimum Steps to Collect All Flowers

Minimum Steps to Collect All Flowers

You are given a rectangular garden represented as a grid with N rows and M columns. Each cell in the grid is either a flower (*), a tree (#), or an empty space (.). You start at the top‐left cell (0, 0). Your task is to determine the minimum number of steps required to collect all the flowers and return to the starting cell.

Important details:

  • You may move one cell per step in any of the four cardinal directions: up, down, left, or right.
  • If the starting cell contains a flower, it is automatically collected without any move.
  • If it is impossible either to reach all the flowers or to return to the start, output -1.

The intended solution performs a breadth-first search (BFS) from the start to compute distances to each flower. The answer is computed as the sum of twice the distance from the start to each flower (since you have to go and come back) provided that every flower is reachable.

inputFormat

The input is provided via standard input (stdin). The first line contains two integers N and M, representing the number of rows and columns of the garden respectively. This is followed by N lines, each containing a string of M characters that represents a row of the garden.

outputFormat

Output a single integer to standard output (stdout) representing the minimum number of steps required to collect all the flowers and return to the starting cell. If it is not possible to collect all flowers and return, output -1.## sample

3 3
*.#
.#.
..*
8

</p>