···11+import fileinput
22+33+INPUT = int(fileinput.input()[0])
44+55+66+def is_open(x, y, input=INPUT):
77+ """Open space if number of 1 bits is even, else wall."""
88+ num = (x * x) + (3 * x) + (2 * x * y) + y + (y * y) + input
99+ return bin(num)[2:].count('1') % 2 == 0
1010+1111+1212+def pathfind(a, b, c, d, max_steps=None):
1313+ """
1414+ Returns length of the shortest path from (a, b) to (c, d)
1515+ and the number of visited locations along the way.
1616+ """
1717+1818+ deltas = [(0, 1), (1, 0), (0, -1), (-1, 0)]
1919+ horizon = [(a, b)]
2020+ seen = set()
2121+ steps = 0
2222+2323+ while horizon:
2424+ new_horizon = []
2525+ for x, y in horizon:
2626+ if x == c and y == d:
2727+ return steps, len(seen)
2828+2929+ seen.add((x, y))
3030+3131+ for dx, dy in deltas:
3232+ nx, ny = x + dx, y + dy
3333+ if is_open(nx, ny) and nx >= 0 and ny >= 0 and (nx, ny) not in seen:
3434+ new_horizon.append((nx, ny))
3535+3636+ if steps == max_steps:
3737+ break
3838+3939+ horizon = new_horizon
4040+ steps += 1
4141+4242+ return steps, len(seen)
4343+4444+4545+print "Fewest steps to reach 31, 39 from 1, 1:", pathfind(1, 1, 31, 39)[0]
4646+print "Distinct locations reached in 50 steps:", pathfind(1, 1, -1, -1, max_steps=50)[1]