#C8620. Minimum Steps to Deliver Packages

    ID: 52623 Type: Default 1000ms 256MiB

Minimum Steps to Deliver Packages

Minimum Steps to Deliver Packages

You are given a grid of size N × M that represents a city map. Each cell in the grid contains an integer. A positive number represents a location where a delivery must be made, a negative number represents an obstacle, and 0 indicates an open road. The delivery van starts at the top-left corner (0, 0) and can only move in four directions: up, down, left, or right.

Your task is to determine the minimum number of steps required to travel from the starting cell to visit all delivery points. In order to plan your route, every time the van reaches one of the delivery points, the journey resets from that point and the remaining deliveries are considered. If at any stage it is not possible to reach a pending delivery location, output \( -1 \).

Note: If there are no delivery points (i.e. no positive numbers in the grid), the answer is 0.

The movements can be represented using the following directions:

[ \text{Up} = (-1, 0),\quad \text{Down} = (1, 0),\quad \text{Left} = (0, -1),\quad \text{Right} = (0, 1) ]

</p>

inputFormat

The input is read from stdin and has the following format:

N M
row1
row2
...
rowN

Where the first line contains two integers N and M (the number of rows and columns respectively). Each of the following N lines contains M space-separated integers representing the grid. A positive integer indicates a delivery point, 0 indicates an open road, and -1 indicates an obstacle.

outputFormat

Output a single integer to stdout which is the minimum number of steps required to visit all delivery points. If it is not possible to reach all delivery locations, output -1.

## sample
3 3
0 1 -1
0 0 2
3 -1 0
6