How do I print a 5×5 two-dimensional array in spiral order?
Is there any formula so that I can print an array of any size in spiral order?
How do I print a 5×5 two-dimensional array in spiral order?
Is there any formula so that I can print an array of any size in spiral order?
Please let me add my single loop answer with complexity
O(n)
. I have observed that during left-right and right-left traverse of the matrix, there is an increase and decrease by one respectively in the row-major index. Similarly, for the top-bottom and bottom-top traverse there is increase and decrease byn_cols
. Thus I made an algorithm for that. For example, given a (3x5) matrix with entries the row-major indexes the print output is:1,2,3,4,5,10,15,14,13,12,11,6,7,8,9
.Code solution:
Given a matrix of chars, implement a method that prints all characters in the following order: first the outer circle, then the next one and so on.
Here's my approach using an Iterator . Note this solves almost the same problem.. Complete code here : https://github.com/rdsr/algorithms/blob/master/src/jvm/misc/FillMatrix.java
I see that no one has use only one
for loop
and without recursion in the code, and so I want to contribute.The idea is like this:
Let's see where we should put the signs (marked by #, and numbers by O):
We can see that, unless the point is at the top-left part, the signs are places at points where the distances to the closest horizontal border and the closest vertical border are the same, while for the top-left part, the distance to the top border is one more than the distance to the left border, with priority given to top-right in case the point is horizontally centered, and to top-left in case the point is vertically centered.
This can be realized in a simple function quite easily, by taking the minimum of (
curRow
andheight-1-curRow
), then the minimum of (curCol
andwidth-1-curCol
) and compare if they are the same. But we need to account for the upper-left case, that is, when the minimum iscurRow
andcurCol
themselves. In that case we reduce the vertical distance accordingly.Here is the C code:
Which outputs:
This is my implementation:
For printing a 2-D matrix consider matrix as a composition of rectangles and/or line where smaller rectangle is fitted into larger one, take boundary of matrix which forms a rectangle to be printed, starting with up-left element each time in each layer; once done with this go inside for next layer of smaller rectangle, in case i don't have a rectangle then it should be line to be printed, a horizontal or vertical. I have pasted the code with an example matrix, HTH.