Spiral Matrix

Leetcode

Problem Statement

Given an m x n matrix, return all elements of the matrix in spiral order.

Example 1:

Input: matrix =

[
    [1,2,3],
    [4,5,6],
    [7,8,9]
]

Output: [1,2,3,6,9,8,7,4,5]

Example 2:

Input: matrix =

[
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10,11,12]
]

Output: [1,2,3,4,8,12,11,10,9,5,6,7]

Constraints:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 10
  • -100 <= matrix[i][j] <= 100
class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { int n = matrix.size(); int m = matrix[0].size(); vector<int> arr; int left = 0, right = m - 1, top = 0, bottom = n - 1; // bounds - inclusive int dir = 0; // 0 -> right, 1 -> down, 2 -> left, 3 -> up int c = 0; int row = 0, col = 0; while (c < n * m) { // left < right && top < bottom if (dir == 0) { for (int i = left; i <= right; i++) { arr.push_back(matrix[row][i]); c++; } top++; col = right; } else if (dir == 1) { for (int i = top; i <= bottom; i++) { arr.push_back(matrix[i][col]); c++; } right--; row = bottom; } else if (dir == 2) { for (int i = right; i >= left; i--) { arr.push_back(matrix[row][i]); c++; } bottom--; col = left; } else { for (int i = bottom; i >= top; i--) { arr.push_back(matrix[i][col]); c++; } row = top; left++; } dir++; dir = dir % 4; } return arr; } };
Home | © 2024 Last Updated: Mar 03, 2024
Buy Me A Coffee