def expandGrid(direct): if direct == "U": gridVisited.insert(0, []) for _ in range(len(gridVisited[1])): gridVisited[0].append('.') posHead[0] = posHead[0] + 1 for i in range(len(posTail)): posTail[i][0] = posTail[i][0] + 1 elif direct == "R": for i in range(len(gridVisited)): gridVisited[i].append('.') elif direct == "D": gridVisited.append([]) tempx = len(gridVisited) - 1 for _ in range(len(gridVisited[0])): gridVisited[tempx].append('.') elif direct == "L": for i in range(len(gridVisited)): gridVisited[i].insert(0, '.') posHead[1] = posHead[1] + 1 for i in range(len(posTail)): posTail[i][1] = posTail[i][1] + 1 def checkDist(): for z in range(9): if z == 0: one = posHead else: one = posTail[z-1] two = posTail[z] tempa = one[1] - two[1] tempb = one[0] - two[0] tempc = tempa + tempb if one[0] == two[0]: if not(tempa == 1 or tempa == -1): if tempa > 0: posTail[z][1] += 1 elif tempa < 0: posTail[z][1] -= 1 elif one[1] == two[1]: if not(tempb == 1 or tempb == -1): if tempb > 0: posTail[z][0] += 1 elif tempb < 0: posTail[z][0] -= 1 elif (tempc == -1 or tempc == 1) and tempb < 0: posTail[z][0] -= 1 posTail[z][1] += 1 elif tempc == 3: posTail[z][0] += 1 posTail[z][1] += 1 elif (tempc == -1 or tempc == 1) and tempb > 0: posTail[z][0] += 1 posTail[z][1] -= 1 elif tempc == -3: posTail[z][0] -= 1 posTail[z][1] -= 1 print(posTail[8]) gridVisited[posTail[8][0]][posTail[8][1]] = '#' gridVisited =[['#']] posHead = [0, 0] posTail = [] for z in range(9): posTail.append([0,0]) with open('in.txt','r') as f: inp = f.read().splitlines(keepends=False) direction = [] distance = [] for i in inp: tempa, tempb = i.split(' ') direction.append(tempa) distance.append(int(tempb)) for x in range(len(direction)): if direction[x] == 'U': for y in range(distance[x]): if posHead[0] == 0: expandGrid("U") posHead[0] -= 1 checkDist() elif direction[x] == 'R': for y in range(distance[x]): if posHead[1] == len(gridVisited[0])-1: expandGrid("R") posHead[1] += 1 checkDist() elif direction[x] == 'D': for y in range(distance[x]): if posHead[0] == len(gridVisited) - 1: expandGrid("D") posHead[0] += 1 checkDist() elif direction[x] == 'L': for y in range(distance[x]): if posHead[1] == 0: expandGrid("L") posHead[1] -= 1 checkDist() visited = 0 for i in gridVisited: for x in i: if x == '#': visited += 1 print(visited)