Problem statement

https://binarysearch.com/problems/2048/

Solution

First of all let us deal with different direction by rotating our grid, then move to the left and then rotate it back. To simulate our move, for each row we use queue: first find all non-zero elements, and then if two leftest element are equal, put sum of them, if not, put one element.

Complexity

It is O(n^2) for time and space.

Code

class Solution:
    def solve(self, board, d):
        def ccw(x, times):
            for _ in range(times):
                x = [[x[i][j] for i in range(4)] for j in range(4)][::-1]
            return x
        
        rot = {"l" : 0, "u" : 1, "r" : 2, "d" : 3}
        board = ccw(board, rot[d[0]])

        for i in range(4):
            row = deque([x for x in board[i] if x])
            ans = []
            while row:
                if len(row) > 1 and row[0] == row[1]:
                    ans += [row.popleft() + row.popleft()]
                else:
                    ans += [row.popleft()]
            ans += [0] * (4 - len(ans))
            board[i] = ans

        board = ccw(board, 4 - rot[d[0]])
        return board