#include <vector>
#include <unordered_map>
#include <queue>
#include <iostream>
using namespace std;
/*
Given n nodes labeled from 0 to n-1 and a list of undirected edges, write a function
to find the number of connected components in an undirected graph.
For example:
0
|
1 ---> 2 4--->3
Given n = 5 and edges = [[0,1], [1, 2], [3, 4]] return 2.
*/
// it is pretty straightforward to come up BFS algorithm.
// But the first task is to change the pair vector into graph node-edges form.
// we can use hashMap to do that. unordered_map<int, vector<int> > hashMap.
void BFS(unordered_map<int, vector<int> >& hashMap, int node, unordered_map<int, bool>& visited) {
queue<int> nodes;
nodes.push(node);
while(!nodes.empty()) {
int tmp = nodes.front();
nodes.pop();
if(visited[tmp]) continue; // if visited, skip it.
visited[tmp] = true;
auto iter = hashMap.find(tmp);
vector<int> edges = iter->second;
for(int k = 0; k < edges.size(); k++) {
nodes.push(edges[k]);
}
}
}
int findNumOfConnectedComponent(int n, vector< vector<int> >& edges) {
unordered_map<int, vector<int> > hashMap;
unordered_map<int, bool> visited;
int count = 0;
for(int i = 0; i < edges.size(); ++i) {
hashMap[edges[i][0]].push_back(edges[i][1]);
hashMap[edges[i][1]].push_back(edges[i][0]);
}
auto iter = hashMap.begin();
while(iter != hashMap.end()) {
visited[iter->first] = false;
iter++;
}
auto it = visited.begin();
while(it != visited.end()) {
if(!(it->second)) {
BFS(hashMap, it->first, visited);
count++;
}
it++;
}
return count;
}
int main(void) {
vector< vector<int> > edges {
{0, 1},
{1, 2},
{3, 4},
{5, 6},
{7, 7}};
cout << findNumOfConnectedComponent(8, edges) << endl;
}
LeetCode 323. Number of Connected Components in an Undirected Graph
最新推荐文章于 2024-05-10 08:14:23 发布