I would like to write a python or c++ function to print numbers like the following examples (with n as input parameter):
When n = 3, print:
1 2 3
8 0 4
7 6 5
When n = 4, print:
4 5 6 7
15 0 1 8
14 3 2 9
13 12 11 10
I have an answer in the following code block, but it is not quite elegant. Does anyone have a better solution?
def print_matrix(n):
l = [i for i in range(0,n*n)]
start = (n-1)/2
end = n-1-start
count = 0
if start ==end:
l [start+ n*end] = count
start -= 1
count +=1
while start >=0:
end = n - start
for i in range(start, end-1):
x= i
y= start
print y*n +x
l[y*n +x] = count
count +=1
for i in range(start, end-1):
x = end-1
y = i
print y*n +x
l[y*n +x] = count
count +=1
for i in range(end-1,start,-1):
x= i
y= end-1
print y*n +x
l[y*n +x] = count
count +=1
for i in range(end-1, start,-1):
x = start
y = i
print y*n +x
l[y*n +x] = count
count +=1
start -=1
print l