Possible algorithms for printing a spiral matrix

let's say we need to print: (for n = 4)

1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7 

this is just a sample for n = 4, the algorithm should be generalized for all integers. I thought and tried to code thinking for the spiral rotation of the indices going here, that is

 element: 1 - 2 - 3 - 4 - 5...->16 indexes: 00-01-02-03-13-23...-21 

but this spiral rotation of the index does not give me enough picture to enter the full algorithm.

then I took a completely different approach by checking the index number. row and column printed sequentially:

  row coloumn 1> 0 -> n-1 2> n-1 -> 0 3> 1 -> n-2 4> n-2 -> 1 

but I'm still stuck in writing an algorithm for this. I don’t want my guys to write down codes in response, so just

correct me in my algorithms mentioned above, or if you have any new algorithm for this, please provide a new way to solve this problem.

-3
source share
2 answers

I had a lot of fun watching my competent teachers come up with apparently clever and short ways to iterate the matrix like spirals, but none of them worked correctly when I implemented them.

So, what I suggest is that you do not think of any scheme or code reduction to do this. You will almost certainly make a mistake and spend a lot of time debugging. Instead, simply simulate the moves using simple conditions and updates:

 1. Move right until you hit the right bonundary, then move one step down if possible and increment the top boundary; 2. Move down until you hit the bottom boundary, then move one step left if possible and decrement the right boundary; 3. Move left until you hit the left boundary, then move one step up if possible and decrement the bottom boundary; 4. Move up until you hit the top boundary, then move one step right if possible and increment the left boundary. Go to step (1). 

This will lead to even more code, but will be much more readable and much less error prone.

+1
source

Think of layers.

In the example of 16 numbers, the layers are as follows:

 1st Layer = 1 2 3 4 ... 12 2nd Layer = 13 14 15 16 

Once you figure out which layers exist, you should be able to convert this to the coordinate (x, y) using the layer number and index into that layer.

You might think about shaping inside out. Just be careful that an even square like 4 ^ 2 will look fundamentally different than an odd square like 5 ^ 2 in math.

Good luck.

+1
source

Source: https://habr.com/ru/post/1214583/


All Articles