Let,
The upper left square $\rightarrow (1, 1)$
Bottom right square $\rightarrow (n, n)$
The object on position $(i, j) \rightarrow S[i][j]$
The maximum amount of fruit we can gain to reach $(i, j)$
from $(1, 1) \rightarrow fruit[i][j]$
The number of paths to reach $(i, j)$
from $(1, 1)$
collecting $fruit[i][j]$
fruits $\rightarrow path[i][j]$
If $S[i][j]$
contains r
, then there is no path to $(i, j)\rightarrow path[i][j] = 0$
Otherwise,
Let $isFruit = 1$
if $S[i][j]$
contains f
and $0$
otherwise.
We can write:
$fruit[i][j] = isFruit + \max(fruit[i-1][j], fruit[i][j-1])$
, and$path[i][j] = \sum\left\lbrace\begin{matrix} 0 & \text{always}\\ path[i-1][j] & \text{if } fruit[i-1][j] + isFruit = fruit[i][j]\\ path[i][j-1] & \text{if } fruit[i][j-1] + isFruit = fruit[i][j] \end{matrix}\right.$
At the beginning,
Set all $path[i][j]$
for $i, j \in \{0, 1, \dots, n\}$
to $0$
.
Set all $fruit[i][j]$
for $i, j \in \{0, 1, \dots, n\}$
to $-\infty$
.
We won't have any fruits: $fruit[1][1] = 0$
.
We assume that there is at least one path: $path[1][1] = 1$
We need to find $fruit[n][n]$
and $path[n][n]$
. If there is no path from top-left to the bottom-right, $path[n][n]$
will be zero and $fruit[n][n]$
will contain a negative value.
Don't forget to use modulo while summing.
Complexity: $O(n^2)$