Going to Meet Sina
InterviewTime limit1sMemory limit128 MB
Given up to 10^4 blocked cells on a bounded grid, find the shortest 4-directional path from (0,0) to (X,Y) avoiding all puddles.
- Level
Medium4 of 10
- Topics
- BFS, Graph, Shortest path, Hash map
- Solved
- No attempts yet
Problem
Kipa set out early in the morning to meet Sina. Heavy rain had fallen overnight, so Kipa put on brand-new rain boots and left home at , only to find that puddles had appeared. The -th puddle is located at , and Kipa knows the position of every puddle.
Kipa wants to reach Sina's house at as quickly as possible, but because the boots are new, Kipa does not want to step on any puddle. Kipa can move only one cell at a time in the four directions up, down, left, and right. Find the minimum travel distance (the number of cells moved) needed to reach Sina's house without stepping on a puddle. Assume it is never necessary to step on a puddle in order to reach Sina's house.
Constraints: , , .
Input
The first line contains , , and , separated by spaces.
Each of the next lines contains the coordinates and of the -th puddle, separated by a space.
Output
Print, on the first line, the minimum travel distance to reach Sina's house without stepping on a puddle.
Hint
Sina's house is at . The figure below shows a situation with 7 puddles. M marks a puddle, B marks Sina's house, and * marks Kipa's starting point .
4 . . . . . . . .
3 . M . . . . . .
Y 2 . . M B M . M .
1 . M . M . M . .
0 . . * . . . . .
-1 . . . . . . . .
-2-1 0 1 2 3 4 5
X
The shortest route is shown by the cells marked * below, and its length is .
4 ******* . . . .
3 * M . * . . . .
Y 2 * . M B M . M .
1 * M . M . M . .
0 ***** . . . . .
-1 . . . . . . . .
-2-1 0 1 2 3 4 5
X