无向图的dfs遍历问题,把求所需要的边数转换成了连通块个数
#include<cstdio>
#include<cstring>
#include<vector>
using namespace std;
const int N = 1010;
vector<int> G[N];
int vis[N];
int n, m, k,query;
void dfs(int v)
{
if (v == query) return;
vis[v] = 1;
for (int i = 0; i < G[v].size(); i++)
{
if (vis[G[v][i]] == 0) dfs(G[v][i]);
}
}
int main()
{
int a, b;
scanf("%d%d%d", &n, &m, &k);
for (int i = 0; i < m; i++)
{
scanf("%d %d", &a, &b);
G[a].push_back(b);
G[b].push_back(a);
}
for (int i = 0; i < k; i++)
{
int num=0;
scanf("%d", &query);
memset(vis, 0, sizeof(vis));
for (int j = 1; j <= n; j++)
{
if (j != query && vis[j] == 0)
{
dfs(j);
num++;
}
}
printf("%d\n", num - 1);
}
return 0;
}