We need to count the number of squares. We can do it in three routines:

  1. Test for one square
  2. Test for all squares on a diagonal
  3. Test for all points
Implementation:
def test_one(grid, ax, ay, bx, by):
    return grid[ay][ax] + grid[by][ax] + grid[ay][bx] == '###'

def test_diag(grid, x, y):
    ox, oy = x, y
    n = 0
    while x > 0 and y > 0:
        x -= 1
        y -= 1
        n += test_one(grid, x, y, ox, oy)
    return n

def test_all(grid):
    n = 0
    for y in range(1, len(grid)):
        for x in range(1, len(grid[0])):
            if grid[y][x] == '#':
                n += test_diag(grid, x, y)
    return n

def parse(txt):
    return txt.strip().split('\n')

print(test_all(parse(open('input.txt').read())))
Time complexity analysis: Decent enough.

Let's look at part 2... Oh bother. I immediately had some ideas, but decided to take a long-overdue shower first and sort my thoughts out.

My solution uses two observations:

Taking any two points gives us 4 parameters: Px, Py, Qx, Qy. We calculate the vector D = Q - P and use that to get two additional points, giving us a perfect square.

We can avoid counting duplicates by collecting the results in a set, but it is much more efficient to ensure Px in [0;Qx] and Py in [0;Qy[.

The solution:

def test_one(points, ax, ay, bx, by):
    dx, dy = bx - ax, by - ay
    return (ax + dy, ay - dx) in points and (bx + dy, by - dx) in points

def test_all(grid):
    points = frozenset((x,y) for y, r in enumerate(grid) for x, c in enumerate(r) if c == '#')
    return sum(
        test_one(points, ax, ay, bx, by)
        for bx, by in points
        for ax, ay in points
        if ax <= bx and ay < by
    )

def parse(txt):
    return txt.strip().split('\n')

print(test_all(parse(open('input.txt').read())))
Time complexity is O(max(N,M2)) where M is the number of trees (points).


Update: A slightly different solution for part 2:

def test_one(points, ax, ay, bx, by):
    dx, dy = bx - ax, by - ay
    return (ax + dy, ay - dx) in points and (bx + dy, by - dx) in points

def test_all(grid):
    n = 0
    points = set((x,y) for y, r in enumerate(grid) for x, c in enumerate(r) if c == '#')
    while points:
        x, y = next(iter(points))
        points.remove((x, y))
        for xx, yy in points:
            n += test_one(points, x, y, xx, yy)
    return n

def parse(txt):
    return txt.strip().split('\n')

print(test_all(parse(open('input.txt').read())))
My initial solution looked like this, but I forgot to remove points (points.remove((x, y))) which led to squares being counted twice.