9.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. from util import get_input
  2. from functools import reduce
  3. input = get_input("9.input")
  4. input = [[int(a) for a in line] for line in input]
  5. def neighbours(map, x, y):
  6. ns = []
  7. if x > 0:
  8. ns.append(map[x - 1][y])
  9. if y > 0:
  10. ns.append(map[x][y - 1])
  11. if x < len(map) - 1:
  12. ns.append(map[x + 1][y])
  13. if y < len(map[0]) - 1:
  14. ns.append(map[x][y + 1])
  15. return ns
  16. lows = []
  17. for x in range(len(input)):
  18. for y in range(len(input[0])):
  19. ns = neighbours(input, x, y)
  20. if len([1 for n in ns if n > input[x][y]]) == len(ns):
  21. lows.append(input[x][y])
  22. print(sum([1 + n for n in lows]))
  23. def basin_size(map, x, y, taken):
  24. if map[x][y] == 9:
  25. return 0
  26. if (x, y) in taken:
  27. return 0
  28. size = 1
  29. taken.add((x, y))
  30. if x > 0:
  31. size += basin_size(map, x - 1, y, taken)
  32. if y > 0:
  33. size += basin_size(map, x, y - 1, taken)
  34. if x < len(map) - 1:
  35. size += basin_size(map, x + 1, y, taken)
  36. if y < len(map[0]) - 1:
  37. size += basin_size(map, x, y + 1, taken)
  38. return size
  39. basins = []
  40. taken = set()
  41. for x in range(len(input)):
  42. for y in range(len(input[0])):
  43. size = basin_size(input, x, y, taken)
  44. if size != 0:
  45. basins.append(size)
  46. basins.sort()
  47. print(reduce(lambda a, b: a * b, basins[-3:]))