def zigzag(n):
    """
    Produce a list of indexes that traverse a matrix of size n * n using the JPEG zig-zag order.
    Taken from https://rosettacode.org/wiki/Zig-zag_matrix#Alternative_version.2C_Translation_of:_Common_Lisp
    
    :param n: size of square matrix to iterate over
    :return: list of indexes in the matrix, sorted by visit order
    """
    def move(i, j):
        if j < (n - 1):
            return max(0, i - 1), j + 1
        else:
            return i + 1, j

    mask = []
    x, y = 0, 0
    for v in range(n * n):
        mask.append((y, x))
        # Inverse: mask[y][x] = v

        if (x + y) & 1:
            x, y = move(x, y)
        else:
            y, x = move(y, x)

    return mask