There is a field with plants — a grid with N rows (numbered 1 through N) and M columns (numbered 1 through M); out of its NM cells, K cells contain plants, while the rest contain weeds. Outside this grid, there are weeds everywhere. Two cells are adjacent if they have a common side.
You want to build fences in the field in such a way that the following conditions hold for each cell that contains a plant:
it is possible to move from this cell to each adjacent cell containing a plant without crossing any fences it is impossible to move from this cell to any cell containing weeds without crossing any fences
Input:
The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains three space-separated integers N, M and K. K lines follow. Each of these lines contains two space-separated integers r and c denoting that the cell in row r and column c contains a plant.
#include <iostream>
#include<vector>
#include<queue>
using namespace std;
int main() {
    // your code goes here
    int t,n,m,i,j,k,flag=0;
    int r[4] = {-1,1,0,0};
    int c[4] = {0,0,-1,1};
    cin>>t;
    while(t--) {
        int ans=0;
        cin>>n>>m>>k;
      vector < vector<int> >  vec(n, vector<int>(m,0));
      /* for(int z=0; z<k; z++) {
            cin>>i>>j;
            vec[i-1][j-1] = 1;
        } */
        queue<pair<int,int>> q;
        for(i=0;i<n;i++) {
            for(j=0;j<m;j++) {
                if(vec[i][j] == 1) {
                    q.push(make_pair(i,j));
                    flag = 1;
                    break;
                }
            }
            if(flag==1)
            break;
        }
        while(!q.empty()) {
            pair<int,int> p = q.front();
            int a = p.first;
            int b = p.second;
          int x=0;
            q.pop();
            for(i=0;i<4;i++) {
                for(j=0;j<4;j++) {
                    int rr = a + r[i];
                    int cc = b + c[j];
                    if(rr<0 || cc<0 || rr>=n || cc>=m || vec[rr][cc]==0)
                    continue;
                    else {
                        q.push(make_pair(rr,cc));
                        x++;
                    }
                }
            }
            ans = ans + (4-x);
        }
         cout<<ans<<endl;
    }
    return 0;
}
If I remove the comments above, it shows timeout error. I'm unable to detect the problem with the above statement.
 
    