Editor Distance
InterviewTime limit2sMemory limit512 MB
Given the character counts of N lines up to 80 wide, find the fewest arrow-key presses to move a cursor from a start position to a finish position, where vertical moves clamp to each line's end.
- Level
Medium7 of 10
- Topics
- Graph, Shortest path, Dynamic programming, Implementation
- Solved
- No attempts yet
Problem
You are editing a program in a text editor and want to move the cursor from one position to another using as few key presses as possible.
The editor behaves as follows:
- The cursor is moved with the four arrow keys: up (↑), down (↓), left (←), and right (→).
- Pressing → moves the cursor one character to the right. If the cursor is on the rightmost character of a line, it moves to the first character of the line below. The cursor does not move if it is already at the bottom-right position.
- Pressing ← moves the cursor one character to the left. If the cursor is on the leftmost character of a line, it moves to the last character of the line above. The cursor does not move if it is already at the top-left position.
- Pressing ↑ moves the cursor to the character directly above it. If there is no character directly above (the line above is shorter), it moves to the last character of the line above. The cursor does not move if it is already on the first line.
- Pressing ↓ moves the cursor to the character directly below it. If there is no character directly below (the line below is shorter), it moves to the last character of the line below. The cursor does not move if it is already on the last line.
Given the number of characters on each line together with a start and a finish position, find the minimum number of key presses needed to move the cursor from the start position to the finish position.
Input
The first line contains , the number of lines in the program ().
Each of the next lines contains one integer: the number of characters on that line. Every line has at least and at most characters.
The next line contains two integers , the starting row and column of the cursor, where and is at most the number of characters on row .
The last line contains two integers , the finishing row and column of the cursor, where and is at most the number of characters on row .
Output
Output a single integer: the minimum number of key presses required to move the cursor from row , column to row , column .