[LeetCode] Minimum Distance to Type a Word Using Two Fingers

1320. Minimum Distance to Type a Word Using Two Fingers

You have a keyboard layout as shown above in the X-Y plane, where each English uppercase letter is located at some coordinate.

  • For example, the letter ‘A’ is located at coordinate (0, 0), the letter ‘B’ is located at coordinate (0, 1), the letter ‘P’ is located at coordinate (2, 3) and the letter ‘Z’ is located at coordinate (4, 1).
    Given the string word, return the minimum total distance to type such string using only two fingers.

The distance between coordinates (x1, y1) and (x2, y2) is |x1 - x2| + |y1 - y2|.

Note that the initial positions of your two fingers are considered free so do not count towards your total distance, also your two fingers do not have to start at the first letter or the first two letters.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
int dis[26][26]{0,};
int dp[301][26][26];
int distance(int a, int b) {
int xa = a % 6, ya = a / 6;
int xb = b % 6, yb = b / 6;
return abs(xa-xb) + abs(ya-yb);
}
int solution(string& word, int p, int finger1, int finger2) {
if(p == word.size()) return 0;
if(dp[p][finger1][finger2] != -1) return dp[p][finger1][finger2];
return dp[p][finger1][finger2] = min(
solution(word, p + 1, min(finger2, word[p] - 'A'), max(finger2, word[p] - 'A')) + dis[finger1][word[p]-'A'],
solution(word, p + 1, min(finger1, word[p] - 'A'), max(finger1, word[p] - 'A')) + dis[finger2][word[p]-'A']
);
}
public:
int minimumDistance(string word) {
memset(dp,-1,sizeof(dp));
for(int i = 0; i < 26; i++) {
for(int j = i + 1; j < 26; j++) {
dis[i][j] = dis[j][i] = distance(i,j);
}
}
int res = INT_MAX;
for(int i = 0; i < 26; i++)
for(int j = i + 1; j < 26; j++) {
res = min(res,solution(word,0,i,j));
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/11/PS/LeetCode/minimum-distance-to-type-a-word-using-two-fingers/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.