323. Number of Connected Components in an Undirected Graph
问题描述:
Given n
nodes labeled from 0
to n - 1
and a list of undirected edges (each edge is a pair of nodes), write a function to find the number of connected components in an undirected graph.
Example 1:
Input:n = 5
andedges = [[0, 1], [1, 2], [3, 4]]
0 3 | | 1 --- 2 4 Output: 2
Example 2:
Input:n = 5
andedges = [[0, 1], [1, 2], [2, 3], [3, 4]]
0 4 | | 1 --- 2 --- 3 Output: 1
Note:
You can assume that no duplicate edges will appear in edges
. Since all edges are undirected, [0, 1]
is the same as [1, 0]
and thus will not appear together in edges
.
解题思路:
建立邻接链表
开始准备dfs该图
首先判断改顶点是否被访问过
若被访问过,则跳过。
若没有被访问过,则从这个顶点开始dfs,然后遍历,对遍历到的每一个点,设其为被访问过。
需要注意的是:要将每个顶点都加入其对应的邻接连表
for(auto e : edges){
adj_list[e.first].push_back(e.second);
adj_list[e.second].push_back(e.first);
}
代码:
class Solution { public: int countComponents(int n, vector<pair<int, int>>& edges) { vector<vector<int>> adj_list(n); for(auto e : edges){ adj_list[e.first].push_back(e.second); adj_list[e.second].push_back(e.first); } vector<bool> visited(n, false); int ret = 0; for(int i = 0; i < n; i++){ if(visited[i]) continue; visited[i] = true; dfs(adj_list, i, visited); ret++; } return ret; } private: void dfs(vector<vector<int>> &adj, int node, vector<bool> &visited){ for(int i = 0; i < adj[node].size(); i++){ if(visited[adj[node][i]]) continue; visited[adj[node][i]] = true; dfs(adj, adj[node][i], visited); } } };