DP but saving time and memory at the same time
Code\n\nclass Solution:\n    def minimumMoves(self, grid: List[List[int]]) -> int:\n        n = len(grid)\n        h = []\n        for i in grid[0][1:]:\n      
# Code\n```\nclass Solution:\n    def minimumMoves(self, grid: List[List[int]]) -> int:\n        n = len(grid)\n        h = []\n        for i in grid[0][1:]:\n            if i == 0:\n                h.append(0)\n            else:\n                h += [float(\'INF\')] * (n - 1 - len(h))\n                break\n\n        v = [float(\'INF\')]\n        for i in range(n-1):\n            if grid[1][i] == 0:\n                v.append(v[-1])\n                if grid[0][i+1] == 0 and grid[1][i+1] == 0:\n                    v[-1] = min(v[-1], h[i] + 1)\n            else:\n                v.append(float(\'INF\'))\n        v.pop(0)\n\n        grid.append([1] * n)\n\n        for i in range(1,n):\n            j = 0\n            if grid[i][0] == 1:\n                h[0],v[0] = float(\'INF\'), float(\'INF\')\n            else:\n                if grid[i][1] == 0 and grid[i+1][0] == 0:\n                    if grid[i+1][1] == 0:\n                        if h[j] < v[j]:\n                            v[j] = h[j] + 1\n                        elif v[j] < h[j]:\n                            h[j] = v[j] + 1\n                elif grid[i][1] == 0:\n                    v[j] = float(\'INF\')\n                elif grid[i+1][j] == 0:\n                    h[j] = float(\'INF\')\n                else:\n                    h[j],v[j] = float(\'INF\'),float(\'INF\')\n            \n            for j in range(1,n - 1):\n                if grid[i][j] == 1:\n                    h[j],v[j] = float(\'INF\'), float(\'INF\')\n                    continue\n                if grid[i][j + 1] == 0 and grid[i+1][j] == 0:\n                    h[j] = min(h[j],h[j-1])\n                    v[j] = min(v[j],v[j-1])\n                    if grid[i+1][j+1] == 0:\n                        if h[j] < v[j]:\n                            v[j] = h[j] + 1\n                        elif v[j] < h[j]:\n                            h[j] = v[j] + 1\n                elif grid[i][j + 1] == 0:\n                    h[j] = min(h[j],h[j-1])\n                    v[j] = float(\'INF\')\n                elif grid[i+1][j] == 0:\n                    v[j] = min(v[j],v[j-1])\n                    h[j] = float(\'INF\')\n                else:\n                    h[j],v[j] = float(\'INF\'),float(\'INF\')\n                \n        res = h[-1] + n * 2 - 3\n        return res if res < float(\'INF\') else -1\n\n\n\n\n\n\n\n\n                    \n\n\n```
['Python3']