
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.

&nbsp;
Example 1:

Input: word = "CAKE"
Output: 3
Explanation: Using two fingers, one optimal way to type "CAKE" is: 
Finger 1 on letter 'C' -&gt; cost = 0 
Finger 1 on letter 'A' -&gt; cost = Distance from letter 'C' to letter 'A' = 2 
Finger 2 on letter 'K' -&gt; cost = 0 
Finger 2 on letter 'E' -&gt; cost = Distance from letter 'K' to letter 'E' = 1 
Total distance = 3


Example 2:

Input: word = "HAPPY"
Output: 6
Explanation: Using two fingers, one optimal way to type "HAPPY" is:
Finger 1 on letter 'H' -&gt; cost = 0
Finger 1 on letter 'A' -&gt; cost = Distance from letter 'H' to letter 'A' = 2
Finger 2 on letter 'P' -&gt; cost = 0
Finger 2 on letter 'P' -&gt; cost = Distance from letter 'P' to letter 'P' = 0
Finger 1 on letter 'Y' -&gt; cost = Distance from letter 'A' to letter 'Y' = 4
Total distance = 6


&nbsp;
Constraints:


	2 &lt;= word.length &lt;= 300
	word consists of uppercase English letters.


from functools import cache
class Solution:
    def minimumDistance(self, word: str) -> int:
        alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        COL = 6
        index = { c:(i//COL, i%COL) for i, c in enumerate(alphabets)}
        def dist(a, b):
            return abs(index[a][0] - index[b][0]) + abs(index[a][1] - index[b][1])
        @cache
        def dfs(lhand, rhand, i):
            if i == len(word): return 0
            res = float('inf')
            res = min(res, dfs(word[i], rhand, i+1)) if lhand == -1 else min(res, dist(lhand, word[i])+dfs(word[i], rhand, i+1))
            res = min(res, dfs(lhand, word[i],i+1)) if rhand == -1 else min(res, dist(word[i], rhand) + dfs(lhand, word[i], i+1))
            return res
        return dfs(-1, -1, 0)
class Solution {
    HashMap<Character,Integer[]> pos;
    int [][][]memo;
    int type(String word,int index,char finger1,char finger2){
        if (index==word.length()) return 0;
        int ans=9999999;
        if (memo[index][finger1-'A'][finger2-'A']!=-1) return memo[index][finger1-'A'][finger2-'A'];
        if (finger1=='['){
            
            ans=Math.min(ans,type(word,index+1,word.charAt(index),finger2));
        }
        else{
            
            Integer [] prev=pos.get(finger1);
            Integer [] curr=pos.get(word.charAt(index));
            int dist=Math.abs(prev[0]-curr[0])+Math.abs(prev[1]-curr[1]);
            ans=Math.min(ans,type(word,index+1,word.charAt(index),finger2)+dist);
        }
        if (finger2=='['){
            ans=Math.min(ans,type(word,index+1,finger1,word.charAt(index)));
        }
        else{
            Integer [] prev=pos.get(finger2);
            Integer [] curr=pos.get(word.charAt(index));
            int dist=Math.abs(prev[0]-curr[0])+Math.abs(prev[1]-curr[1]);
            ans=Math.min(ans,type(word,index+1,finger1,word.charAt(index))+dist);
        }
        memo[index][finger1-'A'][finger2-'A']=ans;
        return ans;
    }
    public int minimumDistance(String word) {
        pos=new HashMap();
        for (int i=0;i<26;i++){
            Integer [] coord={i/6,i%6};
            pos.put((char)('A'+i),coord);
        }
        memo=new int [word.length()]['z'-'a'+3]['z'-'a'+3];
        for (int[][] row : memo) {
            for (int[] rowColumn : row) {
                Arrays.fill(rowColumn, -1);
            }
        }
        return  type(word,0,'[','[');
        }
}
class Solution {
public:
    string alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    unordered_map<char, pair<int, int>> m;
    int distCalc(char a, char b) {
        pair<int, int> p_a = m[a];
        pair<int, int> p_b = m[b];
        
        int x_diff = abs(p_a.first - p_b.first);
        int y_diff = abs(p_a.second - p_b.second);
        
        return x_diff + y_diff;
    }
    int dp[301][27][27];
    int minDist(string word, int i, char finger1_char, char finger2_char) {
        if(i == word.size()) return 0;
       
        if(dp[i][finger1_char - 'A'][finger2_char - 'A'] != -1) return dp[i][finger1_char - 'A'][finger2_char - 'A'];
        
        //finger1
        int op1 =  (finger1_char == '[' ? 0 : distCalc(finger1_char, word[i])) + minDist(word, i + 1, word[i], finger2_char);
        
        //finger2
        int op2 =  (finger2_char == '[' ? 0 : distCalc(finger2_char, word[i])) + minDist(word, i + 1, finger1_char, word[i]);
        
        return dp[i][finger1_char - 'A'][finger2_char - 'A'] = min(op1, op2);
    }
    int minimumDistance(string word) {
        //each letter has choice to be clicked by finger 1 or 2
        
        int row = -1;
        for(int i = 0; i < alpha.length(); i++) {
            int col = i % 6;
            if(col == 0) row++;
            m[alpha[i]] = {row, col};
        }
         memset(dp, -1, sizeof(dp));
         return minDist(word, 0, '[', '[');
    }
};
const dist = function(from, to){
    if(from==-1) return 0; 
    const d1 = Math.abs((from.charCodeAt(0)-65)%6-(to.charCodeAt(0)-65)%6),
          d2 = Math.abs(Math.floor((from.charCodeAt(0)-65)/6)-Math.floor((to.charCodeAt(0)-65)/6));
    return d1 + d2;
}
var minimumDistance = function(word) {

    const dp = new Map();
    
    const dfs = function(i, lpos, rpos){
        if(i==word.length) 
            return 0;
        const key = [i,lpos,rpos].join(',');
        if(dp.get(key)) 
            return dp.get(key);
        dp.set(key, Math.min(dist(lpos,word[i])+dfs(i+1,word[i],rpos), dist(rpos,word[i])+dfs(i+1,lpos,word[i])));
        return dp.get(key);
    }
    return dfs(0, -1, -1);
};
Minimum Distance to Type a Word Using Two Fingers