Maps app~30 min2s · 256 MBtarget O(rows x cols) time, O(rows x cols) spacegrid-bfs
A scooter-sharing app sends a courier across a city grid to collect a parcel. Each cell is either open road or a wall. Every turn costs the courier time, because the scooter has to slow down, so the app prefers a route with few turns over a route with few cells.
Straight rides are free. The courier may start in any direction, and each change of direction after that counts as one turn.
Write fewest_turns(grid).
grid is a list of equal-length strings. . is open road, # is a wall, S is the start and T is the pickup. Both S and T are open.S to T, or -1 when no route exists.Input: grid = ["S.#....", "..#.##.", "..#..#.", "....#..", "##.##.T"]
Output: 4The best route has 16 moves, split into five straight segments.
| Segment | Direction | Moves | Turns so far |
|---|---|---|---|
| 1 | down | 3 | 0 |
| 2 | right | 3 | 1 |
| 3 | up | 3 | 2 |
| 4 | right | 3 | 3 |
| 5 | down | 4 | 4 |
The route has 4 turns, so the output is 4. Fewer turns are not possible here, because the walls force the courier around the wall in the middle.
Input: grid = ["S..#", "...#", "...T"]
Output: 1The courier rides down two cells, turns once, and rides right three cells.
Input: grid = ["S.#", "##T"]
Output: -1Both cells next to S and T are walls, so there is no route and the output is -1.
1 ≤ grid.length ≤ 200 (rows) and 1 ≤ grid[i].length ≤ 200 (columns); all rows have the same lengthgrid[i][j] is ., #, S or T, with exactly one S and one TThe grid has up to 40,000 cells. Trying every route is far too many, since the number of routes grows exponentially. A search over states is enough: a state is a cell and a heading, which gives 160,000 states, and each has 4 moves. The cost of a move is 0 or 1, so a breadth-first search by turn count works in about 640,000 steps.