We first print the top boundary from the colStart to the colEnd and increment the value of rowStart to shift the top boundary to the next segment. In other words, loop will run till rowStart < rowEnd and colStart < colEnd. Step2: We run an outer loop to access each segment, where the loop will end when we reach the innermost segment. Step 1: We declare and initialize four variables to traverse matrix boundaries: rowStart = 0,, rowEnd = m - 1, colStart = 0, colEnd = n - 1. For example, after traversing the outermost segment, the boundaries of the next segment will be rowStart + 1, colEnd - 1, rowEnd -1, and colStart + 1. After each iteration, we reduce the horizontal and vertical boundary size by 1 (Think!). We can use a nested loop for the implementation: an outer loop to traverse each matrix segment and four inner loops to print each element in the segments in a clockwise manner.
I do feel that this code can be made more elegant and some checks may be redundant. means "reversed", and means "except first and last"Īs suggested by I tried implementing a more functional version of the solution. I do not know Scala specifics semantics, but here is an implementation in Python: def column(i, matrix):
# last row and first column handling missing Print(except_first(nth_column(L, matrix)))
So you can a program like this, in pseudocode: def nth_row This allows you to think, as much as possible in terms in concepts (print given row or column maybe reversed) instead of indexes, you find a way to simplify the problem and then establish a trivial base case (matrix empty = do not print)
Last row reversed (again careful on repetions)įirst column reversed omitting both first and lastĪnd then? How to print the inside as a spiral? You just remove the outside, the first and last columns and the first and last items of each row and apply this process again. To print out as a spiral the outermost part of a matrix what do you do? 1 2 3 4įirst row Last column reversed but avoiding repeating 4 That is, you are using an imperative style of programming.įunctional style is more about decomposing the problem in smaller even tiny steps and using recursion where reasonable.