Optimisation needed

I am getting TLE on 3 test cases

Here is my code ->

Hi Harshit
Well to optimize you can combine the three for loops into a single loop since they are independently operating.
So after taking cin input you can put two if clauses, one for each of the extra loops you have created.

No, they can’t be combined .
they are grouping the 1’s and then counting

for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {
          if(pond[i][j]==1 && visited[i][j]==0)
            {
                hash[groupid]=rec(pond,i,j,n,m,visited);
                maxi=max(maxi,hash[groupid]);
                groupid++;
            }  
            if(pond[i][j]==0)
            {
                s.clear();
                if(issafe(pond,i+1,j,n,m))
                {
                    s.insert(pond[i+1][j]);
                }
                if(issafe(pond,i-1,j,n,m))
                {
                    s.insert(pond[i-1][j]);
                }
                if(issafe(pond,i,j+1,n,m))
                {
                    s.insert(pond[i][j+1]);
                }
                if(issafe(pond,i,j-1,n,m))
                {
                    s.insert(pond[i][j-1]);
                }
                int ans=count(pond,i,j,n,m,s,hash);
                maxi=max(maxi,ans);
            }
        }
    }

for pond[i][j] == 1, I am changing the value of pond[i][j] and
for pond[i][j] == 0 I am accessing the changed value of pond .

So I have to access all the 1’s first and then all the 0’s ( and not simultaneously )

Try converting your recursions into iterations then.

Also functions like isSafe can be called inline and need not require an explicit seperate function.