FunctionRacerProblemsRace

Flags in Order

HardGridsPython, JavaScript, TypeScript, Java, C++

field is a map: 0 is a pond, 1 is plain ground, and any larger number is a flag with that number on it. All flag numbers are different.

A runner starts in the top left cell and moves up, down, left or right, never into a pond. The runner has to touch every flag, in increasing order of the numbers. Passing over a flag early is allowed, but it only counts when its turn has come.

Return the fewest steps this takes, or -1 if some flag cannot be reached.

Example 1

field [[1,5,1],[1,0,3],[2,1,1]]
returns 7

Two steps down to flag 2, three steps around the pond to flag 3, then two steps to flag 5.

Example 2

field [[1,0,2]]
returns -1

The pond cuts the runner off from the flag.

Example 3

field [[1,4,3,2]]
returns 5

The first flag is three steps away. Then one step back to flag 3 and one more to flag 4.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Grids problems