#!/usr/bin/env python # -*- coding: utf-8 -*- import sys NORTH, S, W, E = (0, -1), (0, 1), (-1, 0), (1, 0) # directions turn_right = { E: NORTH, NORTH: W, W: S, S: E, } # old -> new direction def spiral(width, height): if width < 1 or height < 1: raise ValueError x, y = width // 2, height // 2 # start near the center dx, dy = S # initial direction matrix = [[None] * width for _ in range(height)] count = 0 while True: count += 1 matrix[y][x] = count # visit # try to turn right new_dx, new_dy = turn_right[dx,dy] new_x, new_y = x + new_dx, y + new_dy if (0 <= new_x < width and 0 <= new_y < height and matrix[new_y][new_x] is None): # can turn right x, y = new_x, new_y dx, dy = new_dx, new_dy else: # try to move straight x, y = x + dx, y + dy if not (0 <= x < width and 0 <= y < height): return matrix # nowhere to go def spiral2(width, height): if width < 1 or height < 1: raise ValueError x, y = width // 2, height // 2 # start near the center dx, dy = S # initial direction mylist = [] matrix = [[None] * width for _ in range(height)] matrix2 = [[None] * width for _ in range(height)] count = 0 matrix2[y][x] = 1 # visit while True: zbr = 0 count += 1 matrix[y][x] = count # visit #print(count) try: if y - 1 >= 0: zbr = zbr + matrix2[y-1][x] #print('- ', zbr) except (IndexError, TypeError): pass try: zbr = zbr + matrix2[y+1][x] #print('- ', zbr) except (IndexError, TypeError): pass try: if x - 1 >= 0: zbr = zbr + matrix2[y][x-1] #print('- ', zbr) except (IndexError, TypeError): pass try: zbr = zbr + matrix2[y][x+1] #print('- ', zbr) except (IndexError, TypeError): pass try: zbr = zbr + matrix2[y+1][x+1] #print('- ', zbr) except (IndexError, TypeError): pass try: if y - 1 >= 0 and x - 1 >= 0: zbr = zbr + matrix2[y-1][x-1] #print('- ', zbr) except (IndexError, TypeError): pass try: if x - 1 >= 0: zbr = zbr + matrix2[y+1][x-1] #print('- ', zbr) except (IndexError, TypeError): pass try: if y - 1 >= 0: zbr = zbr + matrix2[y-1][x+1] #print('- ', zbr) except (IndexError, TypeError): pass if (count == 1): mylist.append(1) else: mylist.append(zbr) matrix2[y][x] = zbr # visit # try to turn right new_dx, new_dy = turn_right[dx,dy] new_x, new_y = x + new_dx, y + new_dy if (0 <= new_x < width and 0 <= new_y < height and matrix[new_y][new_x] is None): # can turn right x, y = new_x, new_y dx, dy = new_dx, new_dy else: # try to move straight x, y = x + dx, y + dy if not (0 <= x < width and 0 <= y < height): #return matrix # nowhere to go return (matrix, matrix2, mylist) def print_matrix(matrix): width = len(str(max(el for row in matrix for el in row if el is not None))) fmt = "{:0%dd}" % width for row in matrix: print(" ".join("_"*width if el is None else fmt.format(el) for el in row)) #print_matrix(spiral(601, 601)) #print_matrix(spiral(5, 5)) aids = spiral2(601,601) #aids = spiral2(5,5) #print_matrix(aids[1]) #print(aids) for item in aids[2]: if item > 265149: print(item) sys.exit()