Matrix arrangement issues in php

前端 未结 6 1096
闹比i
闹比i 2021-02-20 13:07

I would like to know some solutions to such a problem.

It is given a number lets say 16 and you have to arrange a matrix this way

1  2  3  4
12 13 14 5
         


        
6条回答
  •  野性不改
    2021-02-20 14:00

    In python:

    from numpy import *
    
    def spiral(N):
        A = zeros((N,N), dtype='int')
        vx, vy = 0, 1 # current direction
        x, y = 0, -1 # current position
        c = 1
        Z = [N] # Z will contain the number of steps forward before changing direction
        for i in range(N-1, 0, -1):
            Z += [i, i]
        for i in range(len(Z)):
            for j in range(Z[i]):
                x += vx
                y += vy
                A[x, y] = c
                c += 1
            vx, vy = vy, -vx
        return A
    
    print spiral(4)  
    

提交回复
热议问题