I'm trying to implement a value-iteration algorithm to solve a grid-world problem (I'm new to the field). The usual formula that I encounter about the value function V(s) is: $$V(s) = R(s) + max_{a \in A} \sum_{s' \in S} T(s, a, s') V(s')$$ where $S$ is the set of states, $A$ the set of actions, $T$ the transition model
$$T(s, a, s') = P(s_{t+1} = s' | s_t = s, a_t = a)$$ and $R$ the reward function.
Since I'm working on a model-based problem, $T$ and $R$ should be known; the problem is that I don't know how to define (or compute knowing the details of the problem) $R$. If I'm in a state $s$ and take an action $a$ that would make the agent hit a boundary of the grid world, the new state $s'$ will be $s$, and the reward, as defined by the problem, is -5.
On the other hand, if I had arrived in state $s$ through another state, the reward will be -1. So basically, $R(s)$ depends on the previous state and the previous action. How do I represent that in the $V(s)$ formula?