Pergunta

Suppose I have the following matrix with values 1-25 as input to my program.

 1  2  3  4  5
 6  7  8  9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25

The inward spiral should give me the output 13 18 17 12 7 8 9 14 19 24 23 22 21 16 11 6 1 2 3 4 5 10 15 20 25. What could be the logic behind such a program? I tried to start off with the center of the matrix and then increasing the row and column to be traversed at every iteration, but I am kinda stuck here.

Foi útil?

Solução

The part that is being repeated is this "square loop" pattern (read this from a to p):

h i j k l
g       m
f       n
e       o
d c b a p

(Here I've shown a square loop of width 5.)

The core of the solution lies in figuring out how to describe this pattern programmatically. This itself is composed of 4 strips that differ in the starting point and increment: a to d, e to h, i to l, and m to p. In this example, the a to d strip has starting point (4, 5) and increment (-1, 0). The other strips are analogous.

The completely solution involves repeating this pattern with increasing size until the entire square is covered. You start with the center piece, followed by a square loop of width 3, followed by another square loop of width 5, etc.

Depending on what coordinate system you use, you may have to deal with some offset that depends on the size of the full grid.

Licenciado em: CC-BY-SA com atribuição
scroll top