Data Structures & AlgorithmsHardGATE CS · DSA

Print a matrix in spiral order (right, down, left, up, repeat). What is printed?

Print a matrix in spiral order (right, down, left, up, repeat). What is printed?
m = [[90, 11, 62, 33], [40, 71, 82, 13], [10, 81, 22, 63]]
top, bot, l, r, out = 0, len(m) - 1, 0, len(m[0]) - 1, []
while top <= bot and l <= r:
    out += m[top][l:r + 1]; top += 1
    out += [m[i][r] for i in range(top, bot + 1)]; r -= 1
    if top <= bot: out += m[bot][l:r + 1][::-1]; bot -= 1
    if l <= r: out += [m[i][l] for i in range(bot, top - 1, -1)]; l += 1
print(out[6:6 + 4])
  1. A. [81, 22, 10, 40]
  2. B. [22, 10, 81, 40]
  3. C. [10, 81, 22, 40]
  4. D. [22, 81, 10, 40]

Correct answer: D. [22, 81, 10, 40]

The bottom row is read right-to-left and the left column bottom-to-top; the guards stop a single remaining row or column from being read twice. Output: [22, 81, 10, 40].

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic