Faaez Razeen

Spiral Matrix

  • 3 min read
  • Array
  • Matrix
  • LC-Medium

3 years ago

Solution

TimeSpaceExplanation
O(mn)O(1)
def spiralOrder(self, matrix: List[List[int]]) -> List[int]: left, top = 0, 0 right, bottom = len(matrix[0]) - 1, len(matrix) - 1 ans = [] while left <= right and top <= bottom: for c in range(left, right + 1): ans.append(matrix[top][c]) top += 1 for r in range(top, bottom + 1): ans.append(matrix[r][right]) right -= 1 if top <= bottom: for c in range(right, left - 1, -1): ans.append(matrix[bottom][c]) bottom -= 1 if left <= right: for r in range(bottom, top - 1, -1): ans.append(matrix[r][left]) left += 1 return ans

Alternate TS solution w/ 4-part pointer updates

function spiralOrder(matrix: number[][]): number[] { let dir = 'R'; let sr = 0; let sc = 0; let nr = matrix.length - 1; let nc = matrix[0].length - 1; const ans = []; while (sr <= nr && sc <= nc) { for(let c = sc; c <= nc; c++) { ans.push(matrix[sr][c]); } sr++; if (sr > nr) { break; } for(let r = sr; r <= nr; r++) { ans.push(matrix[r][nc]); } nc--; if (nc < sc) { break; } for(let c = nc; c >= sc; c--) { ans.push(matrix[nr][c]); } nr--; if(nr < sr) { break; } for(let r = nr; r >= sr; r--) { ans.push(matrix[r][sc]); } sc++; if (sc > nc) { break; } } return ans; };