Solve a couple of 2017 problems.
This commit is contained in:
56
2017/d12.py
Normal file
56
2017/d12.py
Normal file
@@ -0,0 +1,56 @@
|
||||
from lib import str_to_ints
|
||||
from collections import defaultdict
|
||||
|
||||
|
||||
def get_graph(data):
|
||||
g = defaultdict(set)
|
||||
for line in data.splitlines():
|
||||
fs = str_to_ints(line)
|
||||
l = fs[0]
|
||||
for r in fs[1:]:
|
||||
g[l].add(r)
|
||||
g[r].add(l)
|
||||
return g
|
||||
|
||||
|
||||
def part_1(data):
|
||||
g = get_graph(data)
|
||||
to_visit = [0]
|
||||
seen = set()
|
||||
while to_visit:
|
||||
c = to_visit.pop()
|
||||
if c in seen:
|
||||
continue
|
||||
seen.add(c)
|
||||
for nb in g[c]:
|
||||
to_visit.append(nb)
|
||||
print(len(seen))
|
||||
|
||||
|
||||
def part_2(data):
|
||||
g = get_graph(data)
|
||||
|
||||
group_count = 0
|
||||
seen = set()
|
||||
for c in g.keys():
|
||||
if c in seen:
|
||||
continue
|
||||
group_count += 1
|
||||
to_visit = [c]
|
||||
while to_visit:
|
||||
c = to_visit.pop()
|
||||
if c in seen:
|
||||
continue
|
||||
seen.add(c)
|
||||
for nb in g[c]:
|
||||
to_visit.append(nb)
|
||||
print(group_count)
|
||||
|
||||
|
||||
def main():
|
||||
data = open(0).read().strip()
|
||||
part_1(data)
|
||||
part_2(data)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user