diff options
author | Haidong Ji | 2020-05-16 23:36:25 -0500 |
---|---|---|
committer | Haidong Ji | 2020-05-16 23:36:25 -0500 |
commit | 1cf5ca9ec07e2c3c125f075c10b2ba713dbc7c7c (patch) | |
tree | 2cf0ee84c55e5bb6c4e5a8b38e6c3cd838ae6d81 | |
parent | 6149e6ba6be2d253384d34196826b26c8287610b (diff) |
Connected Components done!
-rw-r--r-- | sources/connected_components.py | 33 | ||||
-rw-r--r-- | tests/test_connected_components.py | 12 |
2 files changed, 45 insertions, 0 deletions
diff --git a/sources/connected_components.py b/sources/connected_components.py new file mode 100644 index 0000000..f09f7dc --- /dev/null +++ b/sources/connected_components.py @@ -0,0 +1,33 @@ +# Uses python3 + +import sys + + +def explore(adj, visited, v): + visited.append(v) + for i in adj[v]: + if i not in visited: + explore(adj, visited, i) + + +def number_of_components(adj): + visited = [] + cc = 0 + for v in range(len(adj)): + if v not in visited: + explore(adj, visited, v) + cc = cc + 1 + return cc + + +if __name__ == '__main__': + input = sys.stdin.read() + data = list(map(int, input.split())) + n, m = data[0:2] + data = data[2:] + edges = list(zip(data[0:(2 * m):2], data[1:(2 * m):2])) + adj = [[] for _ in range(n)] + for (a, b) in edges: + adj[a - 1].append(b - 1) + adj[b - 1].append(a - 1) + print(number_of_components(adj)) diff --git a/tests/test_connected_components.py b/tests/test_connected_components.py new file mode 100644 index 0000000..10d7a23 --- /dev/null +++ b/tests/test_connected_components.py @@ -0,0 +1,12 @@ +import unittest +from sources.connected_components import number_of_components + +class MyTestCase(unittest.TestCase): + def test_something(self): + adj = [[1], [0, 2], [1], []] + + self.assertEqual(2, number_of_components(adj)) + + +if __name__ == '__main__': + unittest.main() |