LeetCode 323. Number of Connected Components in an Undirected Graph
2016-05-06 05:57
435 查看
#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; }
相关文章推荐
- 成为C++高手之轻松理解二进制
- facebook messenger platform指南(完整)
- Launch和Shut Off操作详解 - 每天5分钟玩转 OpenStack(30)
- Launch和Shut Off操作详解 - 每天5分钟玩转 OpenStack(30)
- Launch和Shut Off操作详解 - 每天5分钟玩转 OpenStack(30)
- 动态加载JS(css)文件
- kbmMW实现sql查询(图文并茂)
- JS数组操作大全
- LeetCode 217. Contains Duplicate(检查重复)
- 红米Note LTE刷机记录
- [Python爬虫] Selenium爬取新浪微博移动端热点话题及评论 (下)
- LeetCode 216. Combination Sum III(数字之和)
- 算法基础 - 最长回文子串
- PHP实现畅言留言板和网易跟帖样式
- LeetCode 157: Read N Characters Given Read4
- Array Summary
- LeetCode 159. Longest Substring with At Most Two Distinct Characters
- centos 卸载自带的 java
- windows2003 IIS6.0右键属性没有asp.net选项卡的解决办法
- IO多路复用:select、poll、epoll示例