Although not a DP solution but still it should not give TLE

Here the code runs in O ( n*m ) time which is 1e8 , so why it is giving TLE

yeah it should work it the constraint were bit smaller.
here if we see your solution is taking roughly O(3nm)
which is O(n*m) but because constraint are very tight u code is failing(giving tle).
use dp

Okay sir , thankyou sir !!