Microsoft Interview Question: Print a matrix in spiral fas... | Glassdoor.co.in

Interview Question

Senior Software Development Engineer Interview Redmond, WA (US)

Print a matrix in spiral fashion...so Matrix input example

  (Arrows indicate how the spiral happens...start at first arrow go in circle and move to next arrow...etc.) ->1 1 1 1 1 1 -> 2 2 2 1 1 2 2 2 1 1 1 1 1 1 Output: 11111111111111222222
Answer

Interview Answer

1 Answer

0

for MxN matrix, care should be taken if M > N or vice versa. Essentially its a recursive solution with each cycle going over the origin of a smaller matrix. Think of it as an onion, starting with outer shell and moving inwards. So starting at 0,0 print shell. Next start at 1,1 print shell. Essentially proceed along diagonal of matrix as starting point. The trick is to avoid printing the same element twice. Which I did by using a pointer to last element in diagonal. So if it is an 8x10 matrix. Start printing at 0,0 and have a counter at 8,8 (its actually just the row you got to keep track of and decrement...vice versa if the matrix is taller i.e. M>N so 10x8 matrix).
Next iteration start at 1,1 and decrement pointer to 7,7.
When these two pointers meet, printing is done. Upon reflection..I could have just used rows/2 or cols/2 depending on M>N or not. But it worked.

Interview Candidate on 08-Jul-2015

Add Answers or Comments

To comment on this, Sign In or Sign Up.