Here is the implementation for Grid 1 (AtCoder DP-). The code implements the recurrence relation directly. Each step corresponds to part of the formula. To verify your understanding, pick a small example and trace through the code by hand. Write down the value of each variable at each step. This builds intuition that helps when you face new problems. The modular arithmetic prevents overflow. Apply mod after each addition.
Time complexity: .
Space complexity: or O(m) with row improvement.