#!/bin/python3 import sys #display=True display=False def getChoices(curr,a,b,n1): if display: print('bgn getChoices curr:',curr) result=set() limits=range(n1+1) x,y=curr//30,curr%30 al,bl=[a,a,-a,-a,b,b,-b,-b],[b,-b,b,-b,a,-a,a,-a] xn=[i+x if i+x in limits else -99 for i in al] yn=[i+y if i+y in limits else -99 for i in bl] result={30*xn[i]+yn[i] for i in range(8) if xn[i] in limits and yn[i] in limits} if display: print('end getChoices result:',result) return result def mincalc(a,b,n1): if display: print('bgn mincalc a:',a,' b:',b,' n1:',n1) result=0 target=31*n1 found=False moves=set() choices={0} # set first move to 0,0 # while there are choices that are not expanded, while len(choices-moves) and not found: choices-=moves # remove any location already 'moved' to in past if display: print('moves:',*moves) print('choices:',*choices) nxtchoices=set() for choice in choices: # for each choice, get list of all possible moves moves.add(choice) # get all possible moves from current position, as a 'set' nxtchoices=nxtchoices|getChoices(choice,a,b,n1) if target in nxtchoices: found=True break result+=1 # since we just expanded one level and found nxtchoices choices=nxtchoices if display: print('nxtchoices:',*choices) if not found: result=-1 if display: print('end mincalc result:',result) return result n = int(input().strip()) # your code goes here n1=n-1 mx=[[0 for x in range(n1)] for y in range(n1)] # calculate the minimum moves for only the upper triangle of matrix: for i in range(n1): for j in range(i,n1): # consider only top triangle of n x n matrix. if False and i==1 and j==9: display=True else: display=False mx[i][j]=mincalc(i+1,j+1,n1) # copy values from upper triangle to lower triangle of matrix for i in range(n1): for j in range(0,i): mx[i][j]=mx[j][i] # display the result: for row in mx: for cell in row: print(cell,end=' ') print()