# MATLAB: How do i change these for loops so that I get the right numbers for this “game”

dynamicfor loopfunctiongamemoneypath

So basically I have an R-by-C game board, with certain amount of money placed on each board square. I am asked to start from the top-left corner of the board (r=c=1) and move all the way to the bottom-right corner (r=R, c=C), moving right, down, or diagonal at each step. The diagonal moves are free, but moves right or down, have a \$5 penalty and additionally I cannot collect the money from the cell visited. It says you can only collect the money from each board square that you pass through.
My program is now set up to add the money from the square I am on to the previous amount. I guess I am confused by the wording if you pass through the square does that mean you have to look to the previous square? Here's my function.
function [C,P]= dynamicprogramming(S)C(1,1)=S(1,1);%rowsrows=numel(S(:,1));%columnscolumns=numel(S(1,:));for i=1:rows(end)    for j=1:columns(end)        Options=[-inf -inf -inf];        if j~=1                Options(1)=C(i,j-1)+S(i,j)-5;        end        if i~=1                Options(2)=C(i-1,j)+S(i,j)-5;        end        if i~=1 && j~=1                Options(3)=C(i-1,j-1)+S(i,j);        end        [max_ij,path_ij]=max(Options);        if i~=1 || j~=1         C(i,j)=max_ij;        P(i,j)=path_ij;        end    endend