#include <iostream>
#include <queue>
#include <vector>

using namespace std;

int dx[4] = {0, -1, 1, 0};
int dy[4] = {-1, 0, 0, 1};

int main() 
{
    int t;
    cin >> t;

    while (t--) 
    {
        int b, a, chu;
        cin >> b >> a >> chu;

        vector<vector<int>> field(b, vector<int>(a, 0));
        vector<vector<int>> visited(b, vector<int>(a, 0));

        for (int i = 0; i < chu; i++) 
        {
            int x, y;
            cin >> x >> y;
            field[x][y] = 1;
        }

        int cnt = 0;
        queue<pair<int, int>> q;

        for (int i = 0; i < b; i++) 
        {
            for (int j = 0; j < a; j++) 
            {
                if (field[i][j] == 1 && !visited[i][j]) 
                {
                    cnt++;
                    visited[i][j] = 1;
                    q.push({i, j});

                    while (!q.empty()) 
                    {
                        auto cur = q.front();
                        q.pop();

                        for (int d = 0; d < 4; d++) 
                        {
                            int nx = cur.first + dx[d];
                            int ny = cur.second + dy[d];

                            if (nx < 0 || ny < 0 || nx >= b || ny >= a){
                                continue;
                            }
                            if (field[nx][ny] == 1 && !visited[nx][ny]) 
                            {
                                visited[nx][ny] = 1;
                                q.push({nx, ny});
                            }
                        }
                    }
                }
            }
        }

        cout << cnt << '\n';
    }

    return 0;
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: