Documente Academic
Documente Profesional
Documente Cultură
Example:
input: inputMatrix = [ [1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
output: [1, 2, 3, 4, 5, 10, 15, 20, 19, 18, 17, 16, 11, 6, 7, 8, 9,
14, 13, 12]
See the illustration below to understand better what a clockwise spiral order looks
like.
Constraints:
The general idea of the solution is to copy the 4 edges of the spiral rim we currently at
and then move on to copy the next (inner) rim. We keep doing that until we reached to
the end of the spiral. We copy edges in the following order:
Copy the uppermost row from left to right.
Copy the rightmost column from top to bottom.
Copy the lowermost row from right to left.
Copy the leftmost column from bottom to top.
In order to figure what is the next row/column to copy in the spiral order we maintain
4 indices:
Pseudocode:
function spiralCopy(inputMatrix):
numRows = inputMatrix.length
numCols = inputMatrix[0].length
topRow = 0
btmRow = numRows - 1
leftCol = 0
rightCol = numCols - 1
result = []
result.push(inputMatrix[topRow][i])
topRow++
result.push(inputMatrix[i][rightCol])
rightCol--
result.push(inputMatri[btmRow][i])
btmRow--
result.push(inputMatrix[i][leftCol])
leftCol++
return result
Space Complexity: we used an auxiliary array of size N∙M as a return value, hence the
space complexity is O(N∙M). This is a linear space complexity since the size of the
input is O(N∙M) as well.