--- id: 69b5b2be76ec8135a7fbe974 title: "Challenge 245: Spiral Matrix" challengeType: 29 dashedName: challenge-245 --- # --description-- Given a 2D matrix, return a flat array with all of its values in clockwise order. The returned array should have the top-left value first, move right along the top row, then down the right column, then left along the bottom row, then up the left column. Repeat inward for any remaining layers. For example, given: ```json [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] ``` Return `[1, 2, 3, 6, 9, 8, 7, 4, 5]`. # --hints-- `spiral_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])` should return `[1, 2, 3, 6, 9, 8, 7, 4, 5]`. ```js ({test: () => { runPython(` from unittest import TestCase TestCase().assertEqual(spiral_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), [1, 2, 3, 6, 9, 8, 7, 4, 5])`) }}) ``` `spiral_matrix([["a", "b", "c", "d"], ["l", "m", "n", "e"], ["k", "p", "o", "f"], ["j", "i", "h", "g"]])` should return `["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p"]`. ```js ({test: () => { runPython(` from unittest import TestCase TestCase().assertEqual(spiral_matrix([["a", "b", "c", "d"], ["l", "m", "n", "e"], ["k", "p", "o", "f"], ["j", "i", "h", "g"]]), ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p"])`) }}) ``` `spiral_matrix([[True, False, False], [False, True, True], [False, True, False], [True, True, False]])` should return `[True, False, False, True, False, False, True, True, False, False, True, True]`. ```js ({test: () => { runPython(` from unittest import TestCase TestCase().assertEqual(spiral_matrix([[True, False, False], [False, True, True], [False, True, False], [True, True, False]]), [True, False, False, True, False, False, True, True, False, False, True, True])`) }}) ``` `spiral_matrix([[25, 24, 23, 22, 21], [10, 9, 8, 7, 20], [11, 2, 1, 6, 19], [12, 3, 4, 5, 18], [13, 14, 15, 16, 17]])` should return `[25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]`. ```js ({test: () => { runPython(` from unittest import TestCase TestCase().assertEqual(spiral_matrix([[25, 24, 23, 22, 21], [10, 9, 8, 7, 20], [11, 2, 1, 6, 19], [12, 3, 4, 5, 18], [13, 14, 15, 16, 17]]), [25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1])`) }}) ``` # --seed-- ## --seed-contents-- ```py def spiral_matrix(matrix): return matrix ``` # --solutions-- ```py def spiral_matrix(matrix): result = [] top, bottom = 0, len(matrix) - 1 left, right = 0, len(matrix[0]) - 1 while top <= bottom and left <= right: for i in range(left, right + 1): result.append(matrix[top][i]) top += 1 for i in range(top, bottom + 1): result.append(matrix[i][right]) right -= 1 if top <= bottom: for i in range(right, left - 1, -1): result.append(matrix[bottom][i]) bottom -= 1 if left <= right: for i in range(bottom, top - 1, -1): result.append(matrix[i][left]) left += 1 return result ```