Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help with spiral matrix

I need to write a program for Pascal that makes array in spiral form like this:

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

Start from 1 and continue to 36 but this is not so important.

After 3 days thinking I have no idea how to realize this.

Problem is not in language syntax or arrays, it is just in the algorithm.

Can you help me with any ideas, links, pseudo-code or program code in any programming language?

like image 356
Rockstar Avatar asked Feb 15 '26 03:02

Rockstar


1 Answers

Think of splitting the nxn matrix into concentric submatrixes of 2x2, 4x4, .. nxn. In your case we would have the outer sub-matrix (elements 5 to 16) and the inner one (elements 1 to 4).

Now, for each level you should iterate over the four edges, and fill them with the needed elements. You can go inside-out or outside-in. I will go outside-in. We keep a counter which is initially n*n (16 in our example).

For i going from 1 to n/2:

First take the bottom edge (elements 16-13 for outer level). We go from x[n-i+1][i] to x[n-i+1][n-i+1] and fill (this would be 16, 15, 14, 13 for the first level and 4,3 for the second level)

Then we take the right edge (elements 12-10 for outer level). We go from x[n-i][n-i+1] to x[i][n-i+1] (elements 12, 11, 10 for outer level).

Then we take the top edge (elements 9-7 for outer level). We go from x[i][n-i] to x[i][i] (elements 9, 8, 7 for outer level)

At last we take the left edge (elements 6-5 for outer level). We go from x[i+1][i] to x[n-i][i] and fill that side (this would be 6, 5 for outer level).

And at last you have the middle element if n is odd. Then all you have to do is to assign x[n/2+1][n/2+1] = 1

I hope I made the the idea clear; if there is something you don't understand, ask.

Also I didn't implement the solution because I assume that the problem you have is only the idea, not the implementation

like image 53
Gabi Purcaru Avatar answered Feb 17 '26 17:02

Gabi Purcaru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!