Polski

Shortest path in a maze

A warehouse robot looks for the shortest route on a grid with obstacles. BFS in an unweighted graph – and why breadth-first rather than depth-first.

medium · typescript · javascript · python · csharp · java · go · 20 XP

A warehouse robot moves on a grid: . is a free cell, # is a shelf, S is the start and E is the charging station. In one move the robot steps to the neighbouring cell up, down, left or right. How many moves does it need to reach the station?

Task

The function gets the grid as a list of equally long strings (exactly one S and one E) and returns the minimum number of moves from S to E, or -1 when the station cannot be reached. S and E cells are free.

Signatures: shortestPath(grid) (JS/TS), shortest_path(grid) (Python), Solution.ShortestPath (C#, string[]), Solution.shortestPath (Java, String[]), ShortestPath (Go, []string).

Examples

GridResult
["S.E"]2
["SE"]1
["S#E", ".#.", "..."]6 – around the shelf
["S#E"]-1

Constraints

  • 1 ≤ rows, columns ≤ 400 (up to 160,000 cells); a route can be tens of thousands of moves long.

Expected complexity

O(R · C) time, O(R · C) memory.