Happiness is Mandatory
C (gcc), 339 337 331  323 bytes


Saved two eight fifteen sixteen bytes thanks to ceilingcat.




C,a,l,A,m,i,t,o,u,s;n(e,z,Z)int*e;{for(C=1;C;C+=i)for(C=s=0;s&lt;Z;s++)for(u=0;u&lt;z;u++)if(u&gt;8&amp;s&gt;5)for(m=e[~-u+~-s*z],A=i=1;++A&lt;4;)for(o=0;o&lt;7;o++)for(t=0;t&lt;10;t++)a=e[l=u+t-9+(s+o-6)*z],(o-1||t-3&amp;&amp;t-6)*(o-3||t&lt;4|5&lt;t)*(o-4||t&lt;2|3&lt;t&amp;t&lt;6|7&lt;t)*(o-5||t-1&amp;&amp;t-8)?o&gt;1|t&gt;1&amp;t&lt;8&amp;o&lt;2|o&gt;3&amp;o&lt;6|t&amp;&amp;t&lt;9&amp;&amp;(i*=a-m):A&lt;3?i*=a==m:i?e[l]=rand():e;}


Try it online!