# Problem Description
The problem involves transforming a given 2D integer matrix by applying a sequence of directional operations. The operations are encoded as strings ("L", "R", "U", "D"), which stand for left, right, up, and down, respectively. Each operation modifies the matrix in a specific way by summing values either by rows or columns and placing the results in a specific boundary row or column, while setting all other cells to zero.

# Visual Facts
1. The input matrix is a mxn grid of integers (0s and 1s).
2. There are four possible operations: "U" (Up), "D" (Down), "L" (Left), "R" (Right).
3. Each operation transforms the matrix by summing values and placing the results in a specific boundary row or column:
   - "U": Sums each column and places the results in the first row.
   - "D": Sums each column and places the results in the last row.
   - "L": Sums each row and places the results in the leftmost column.
   - "R": Sums each row and places the results in the rightmost column.
4. After placing the sums, all other cells in the matrix are set to zero.

# Visual Patterns
1. **Up (U) Operation**:
   - Sum each column.
   - Place the sums in the first row.
   - Set all other rows to zero.
   - Example: 
     ```
     Input:  [[1, 0, 0],
              [1, 1, 1],
              [1, 0, 1]]
     Output: [[3, 1, 2],
              [0, 0, 0],
              [0, 0, 0]]
     ```

2. **Down (D) Operation**:
   - Sum each column.
   - Place the sums in the last row.
   - Set all other rows to zero.
   - Example: 
     ```
     Input:  [[1, 0, 0],
              [1, 1, 1],
              [1, 0, 1]]
     Output: [[0, 0, 0],
              [0, 0, 0],
              [3, 1, 2]]
     ```

3. **Left (L) Operation**:
   - Sum each row.
   - Place the sums in the leftmost column.
   - Set all other columns to zero.
   - Example: 
     ```
     Input:  [[1, 0, 0],
              [1, 1, 1],
              [1, 0, 1]]
     Output: [[1, 0, 0],
              [3, 0, 0],
              [2, 0, 0]]
     ```

4. **Right (R) Operation**:
   - Sum each row.
   - Place the sums in the rightmost column.
   - Set all other columns to zero.
   - Example: 
     ```
     Input:  [[1, 0, 0],
              [1, 1, 1],
              [1, 0, 1]]
     Output: [[0, 0, 1],
              [0, 0, 3],
              [0, 0, 2]]
     ```


# Solution
from typing import List

def solution(matrix: List[List[int]], operations: List[str]) -> List[List[int]]:
    """
    Transforms a matrix by applying a sequence of directional operations.

    Args:
        matrix: A 2D integer matrix (size M*N) represented as a list of lists.
        operations: A list of operations encoded as strings ("L", "R", "U", "D").

    Returns:
        The transformed matrix after applying all operations in sequence.
    """
    rows = len(matrix)
    cols = len(matrix[0])

    def move_up(mat):
        """Set the first row to the sum of each column, and set the rest to 0."""
        new_mat = [[0] * cols for _ in range(rows)]  # Initialize a new matrix with all zeros
        for col in range(cols):
            col_sum = sum(mat[row][col] for row in range(rows))  # Calculate the sum of the column
            new_mat[0][col] = col_sum  # Set the first row to the column sum
        return new_mat

    def move_down(mat):
        """Set the last row to the sum of each column, and set the rest to 0."""
        new_mat = [[0] * cols for _ in range(rows)]  # Initialize a new matrix with all zeros
        for col in range(cols):
            col_sum = sum(mat[row][col] for row in range(rows))  # Calculate the sum of the column
            new_mat[rows - 1][col] = col_sum  # Set the last row to the column sum
        return new_mat

    def move_left(mat):
        """Set the first column to the sum of each row, and set the rest to 0."""
        new_mat = [[0] * cols for _ in range(rows)]  # Initialize a new matrix with all zeros
        for row in range(rows):
            row_sum = sum(mat[row][col] for col in range(cols))  # Calculate the sum of the row
            new_mat[row][0] = row_sum  # Set the first column to the row sum
        return new_mat

    def move_right(mat):
        """Set the last column to the sum of each row, and set the rest to 0."""
        new_mat = [[0] * cols for _ in range(rows)]  # Initialize a new matrix with all zeros
        for row in range(rows):
            row_sum = sum(mat[row][col] for col in range(cols))  # Calculate the sum of the row
            new_mat[row][cols - 1] = row_sum  # Set the last column to the row sum
        return new_mat

    # Apply each operation in sequence
    for op in operations:
        if op == "U":
            matrix = move_up(matrix)
        elif op == "D":
            matrix = move_down(matrix)
        elif op == "L":
            matrix = move_left(matrix)
        elif op == "R":
            matrix = move_right(matrix)

    return matrix


# Test Script
def test():
    test_cases = [
        {
            "matrix": [
                [1, 0, 0],
                [1, 0, 1],
                [1, 1, 1]
            ],
            "operations": ["U"],
            "expected": [
                [3, 1, 2],
                [0, 0, 0],
                [0, 0, 0]
            ]
        },
        {
            "matrix": [
                [1, 0, 0],
                [0, 1, 0],
                [1, 1, 1]
            ],
            "operations": ["R"],
            "expected":  [[0, 0, 1], [0, 0, 1], [0, 0, 3]]
        },
        {
            "matrix": [
                [1, 0, 0],
                [0, 1, 0],
                [1, 1, 1]
            ],
            "operations": ["D", "L"],
            "expected": [[0, 0, 0], [0, 0, 0], [5, 0, 0]]
        },
        {
            "matrix": [
                [1, 0, 0],
                [1, 0, 1],
                [1, 1, 1]
            ],
            "operations": ["U","L","D","R"],
            "expected": [[0, 0, 0], [0, 0, 0], [0, 0, 6]]
        },
        {
            "matrix": [
                [1, 1, 1],
                [0, 1, 1],
                [0, 0, 1]
            ],
            "operations": ["D","L"],
            "expected": [[0, 0, 0], [0, 0, 0], [6, 0, 0]]
        },
        {
            "matrix": [
                [1, 1, 1],
                [0, 1, 1],
                [0, 0, 1]
            ],
            "operations": ["D","L","R","U"],
            "expected": [[0, 0, 6], [0, 0, 0], [0, 0, 0]],
        },
        {
            "matrix": [
                [1, 1, 1],
                [0, 0, 1],
                [1, 0, 1]
            ],
            "operations": ["D","R"],
            "expected": [[0, 0, 0], [0, 0, 0], [0, 0, 6]]
        },
        {
            "matrix": [
                [1, 1, 1, 1, 0],
                [0, 0, 1, 0, 0],
                [1, 0, 1, 1, 1],
                [1, 0, 0, 1, 1]
            ],
            "operations": ["D"],
            "expected": [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [3, 1, 3, 3, 2]]
        },
                {
            "matrix": [
                [1, 1, 1, 1, 0],
                [0, 0, 1, 0, 0],
                [1, 0, 1, 1, 1],
                [1, 0, 0, 1, 1]
            ],
            "operations": ["D","R","U","L"],
            "expected":[[12, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
        },
                {
            "matrix": [
                [1, 1, 1, 1, 0],
                [0, 0, 1, 0, 0],
                [1, 0, 1, 1, 1],
                [1, 0, 0, 1, 1]
            ],
            "operations": ["D","D","R","U"],
            "expected": [[0, 0, 0, 0, 12], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
        },
    ]

    for i, test_case in enumerate(test_cases, start=1):
        matrix = test_case["matrix"]
        operations = test_case["operations"]
        expected = test_case["expected"]
        
        try:
            output = solution(matrix, operations)
        except Exception as e:
            error_message = (
                f"An exception occurred while running the test case:\n"
                f"`matrix`: {matrix}\n"
                f"`operations`: {operations}\n\n"
                f"Exception: '{str(e)}'"
            )
            assert False, error_message

        if output != expected:
            error_message = (
                f"The following Test Case failed:\n"
                f"`matrix`: {matrix}\n" 
                f"`operations`: {operations}\n\n"
                f"Actual Output: {output}\n"
                f"Expected Output: {expected}"
            )
            assert False, error_message

test()