#include <bits/stdc++.h>
using namespace std;
int mark[110000];
void dfs(vector<int> graph[],int num){
mark[num]=1;
for (int i=0; i<graph[num].size(); i++)
if (!mark[graph[num][i]]){
mark[graph[num][i]]=1;
dfs(graph,graph[num][i]);
}
}
int main(){
int t;
cin>>t;
while (t--){
int n,m,count=0;
cin>>n>>m;
vector<int> graph[n+1];
for (int i=0; i<m; i++){
int p,q;
cin>>p>>q;
graph[p].push_back(q);
graph[q].push_back(p);
}
memset(mark,0,sizeof(mark));
for (int i=1; i<=n; i++){
if (!mark[i]){
++count;
dfs(graph,i);
}
}
cout<<count-1<<endl;
}
return 0;
}
I2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7CmludCBtYXJrWzExMDAwMF07CnZvaWQgZGZzKHZlY3RvcjxpbnQ+IGdyYXBoW10saW50IG51bSl7CiAgICBtYXJrW251bV09MTsKICAgIGZvciAoaW50IGk9MDsgaTxncmFwaFtudW1dLnNpemUoKTsgaSsrKQogICAgICAgIGlmICghbWFya1tncmFwaFtudW1dW2ldXSl7CiAgICAgICAgICAgIG1hcmtbZ3JhcGhbbnVtXVtpXV09MTsKICAgICAgICAgICAgZGZzKGdyYXBoLGdyYXBoW251bV1baV0pOwogICAgICAgIH0KfQppbnQgbWFpbigpewogICAgaW50IHQ7CiAgICBjaW4+PnQ7CiAgICB3aGlsZSAodC0tKXsKICAgICAgICBpbnQgbixtLGNvdW50PTA7CiAgICAgICAgY2luPj5uPj5tOwogICAgICAgIHZlY3RvcjxpbnQ+IGdyYXBoW24rMV07CiAgICAgICAgZm9yIChpbnQgaT0wOyBpPG07IGkrKyl7CiAgICAgICAgICAgIGludCBwLHE7CiAgICAgICAgICAgIGNpbj4+cD4+cTsKICAgICAgICAgICAgZ3JhcGhbcF0ucHVzaF9iYWNrKHEpOwogICAgICAgICAgICBncmFwaFtxXS5wdXNoX2JhY2socCk7CiAgICAgICAgfQogICAgICAgIG1lbXNldChtYXJrLDAsc2l6ZW9mKG1hcmspKTsKICAgICAgICBmb3IgKGludCBpPTE7IGk8PW47IGkrKyl7CiAgICAgICAgICAgIGlmICghbWFya1tpXSl7CiAgICAgICAgICAgICAgICArK2NvdW50OwogICAgICAgICAgICAgICAgZGZzKGdyYXBoLGkpOwogICAgICAgICAgICB9CiAgICAgICAgfQogICAgICAgIGNvdXQ8PGNvdW50LTE8PGVuZGw7CiAgICB9CiAgICByZXR1cm4gMDsKfQ==