中级农民
- 积分
- 124
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2011-4-9
- 最后登录
- 1970-1-1
|
注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
A sparse matrix and find the connected components using multi threading
using all the cores.
execution time criteria 3 s => good, 2s =>great 700 ms => excellent
下面是单线程,而且输入的图是adjancency list
//5763 ms, method: bfs, 时间O(N + E),空间O(N)。
public List<List<Integer>> connectedSet(ArrayList<UndirectedGraphNode> nodes) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
Set<UndirectedGraphNode> visited = new HashSet<>();
for (UndirectedGraphNode node : nodes) {
if (!visited.contains(node)) {
path.clear();
Queue<UndirectedGraphNode> queue = new LinkedList<>();
queue.offer(node);
visited.add(node);
path.add(node.label);
while (!queue.isEmpty()) {
UndirectedGraphNode p = queue.poll();
for (UndirectedGraphNode v : p.neighbors) {
if (!visited.contains(v)) {
visited.add(v);
queue.offer(v);
path.add(v.label);
}
}
}
Collections.sort(path);
res.add(new ArrayList<Integer>(path));
}
}
return res;
}
//7451 ms, method: dfs, 时间O(N + E),空间O(N)
public List<List<Integer>> connectedSet2(ArrayList<UndirectedGraphNode> nodes) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
Set<UndirectedGraphNode> visited = new HashSet<>();
for (UndirectedGraphNode p : nodes) {
if (!visited.contains(p)) {
dfs(p, visited, path);
Collections.sort(path);
res.add(new ArrayList<Integer>(path));
path.clear();
}
}
return res;
}
private void dfs(UndirectedGraphNode p, Set<UndirectedGraphNode> visited, List<Integer> path) {
visited.add(p);
path.add(p.label);
for (UndirectedGraphNode v : p.neighbors) {
if (!visited.contains(v))
dfs(v, visited, path);
}
}
|
上一篇: 有没有Davis附近的小伙伴一起刷题下一篇: 只刷easy & medium的题
|