#include <iostream> using namespace std; //鄰接矩陣存儲圖 //深度優先搜索遍歷圖 //攻佔掉一個點後,計算圖的連通份量的個數 int v[1001][1001]; bool visit[1001];//記錄該點是否被訪問過 int n; //遞歸形式的深度優先搜索 void dfs(int node) { visit[node] = true; for (int i = 1;i <= n;i++) { if (!visit[i] && v[node][i]==1) dfs(i); } } int main() { int m, k; scanf("%d %d %d", &n, &m, &k); //cin >> n >> m >> k;//n座城市,m條路,k個檢查城市 for (int i = 0;i < m;i++) { int a, b; scanf("%d %d", &a, &b); //cin >> a >> b; v[a][b] = 1; v[b][a] = 1; } while (k--) { fill(visit, visit + 1001, false);//初始化爲false int g, cnt = 0; scanf("%d", &g); //cin >> g; visit[g] = true; for (int i = 1;i <= n;i++) { if (!visit[i]) { dfs(i); cnt++; } } printf("%d\n", cnt - 1); //cout << cnt - 1 << endl; } return 0; }
參考博客:https://blog.csdn.net/whl_program/article/details/77627856node