My Coding >
Programming language >
Python >
Exercise >
Spiral matrix
Spiral matrixPrint out table n×n with values from 1 to n2 started from top-left corner and spirally go towards the centre of this table. For example for N=5 we should have this table:
Solution for spiral matrixStep 1: Create movement direction matrix, which will be added to current location. Step 2: After filling first line with values from 1 to n, you can easily notice, that the lengs of the next two lines will be ‘n-1’, then next two lines will be ‘n-2’ etc...until we fill ‘n2’ cells Step 3: If you think, then this algorithm can easily be transformed to any n×m table, by length of travel ‘m-1’ and ‘n-1’ after first line, then ‘m-2’ and ‘n-2’ and so on, until we fill ‘n*m’ cells. Python codeThis is working Python code implementing this simple algorithm for n×n table
Another solution for spiral matrixIdea is very simple. Create table n×n with 0 in every cell. Start from top-left corner and place increasing counter in every cell with 0 inside. If the table border is reached, or cell value is non-zero, turn and continue. If the first cell after turn is non-zero, then stop – job done. This algorithm perfectly works for tables of n×n and n×m sizes.
|
Last 10 artitles
9 popular artitles
|
|
© 2020 MyCoding.uk -My blog about coding and further learning. This blog was writen with pure Perl and front-end output was performed with TemplateToolkit. |