[Python] Solution with Explanation - A Different Point of View
\ndef minimumDistance(self, word: str) -> int:\n    orda = ord(\'A\')\n    pos = {}\n    for i in range(26):\n        pos[chr(orda + i)] = divmod(i, 6)\n       
```\ndef minimumDistance(self, word: str) -> int:\n    orda = ord(\'A\')\n    pos = {}\n    for i in range(26):\n        pos[chr(orda + i)] = divmod(i, 6)\n        \n    N = len(word)\n    \n    def dist(i, j):\n        if i == 0 or j == 0:\n            return 0\n        a, b = word[i - 1], word[j - 1]\n        i1, j1 = pos[a]\n        i2, j2 = pos[b]\n        return abs(i1 - i2) + abs(j1 - j2)\n    \n    dp = [[0] * (N + 1) for _ in range(N + 1)]\n    \n    # Because of symmetry, dp[i][j] represent the minimum total distance when the current position is at i (so one finger must be at i-th letter) and another figure is at j-th letter. \n\t# Here we label the first letter in the sequence as 1. So the maximum value of i is N. 0 is reserved for the initial state.\n\n    # The distance value becomes positive only from the 2nd letter\n    for i in range(2, N + 1):\n        # To get to the state of (i, j) where j = 0, 1, ..., i - 2, the only possible way is to move from the figure at i - 1 to i \n        for j in range(i - 1):\n            dp[i][j] = dp[i - 1][j] + dist(i, i - 1)\n        # To get to the state of (i, i - 1), the last state can be (i - 1, k) where k can be 0, 1, ..., i - 2 \n        dp[i][i - 1] = min([(dp[i - 1][k] + dist(i, k)) for k in range(i - 1)])\n        \n    # dp[N][N] is not a valid state\n    return min(dp[-1][:N])\n```\n\n\t\nOf course it can be compressed to use only 1D dp array\n```\n    def minimumDistance(self, word: str) -> int:\n        orda = ord(\'A\')\n        pos = {}\n        for i in range(26):\n            pos[chr(orda + i)] = divmod(i, 6)\n            \n        N = len(word)\n        \n        def dist(i, j):\n            if i == 0 or j == 0:\n                return 0\n            a, b = word[i - 1], word[j - 1]\n            i1, j1 = pos[a]\n            i2, j2 = pos[b]\n            return abs(i1 - i2) + abs(j1 - j2)\n        \n        dp = [0] * (N + 1)\n    \n        for i in range(2, N + 1):\n            dp[i - 1] = min([(dp[k] + dist(i, k)) for k in range(i - 1)])\n\n            for j in range(i - 1):\n                dp[j] = dp[j] + dist(i, i - 1)\n            \n        return min(dp[:N])\n\t\t```
[]