Monday, March 7, 2022

LeetCode 54. Spiral Matrix

 54. Spiral Matrix


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) {
vector<int> ans;
int m = matrix.size();
int n = matrix[0].size();
vector<vector<bool>> check(m, vector<bool>(n, false));
int x = 0;
int y = 0;
int dx = 0;
int dy = 1;
while(ans.size() < m * n){
ans.push_back(matrix[x][y]);
check[x][y] = true;
x += dx;
y += dy;
// right
if(x >= m or (x < m and dx == 1 and check[x][y])){x--; y--; dx = 0; dy = -1;}
if(x < 0 or (x >= 0 and dx == -1 and check[x][y])){x++; y++; dx = 0; dy = 1;}
if(y >= n or (y < n and dy == 1 and check[x][y])){x++; y--; dx = 1; dy = 0;}
if(y < 0 or (y >= 0 and dy == -1 and check[x][y])) {x--; y++; dx = -1; dy = 0;}
}
return ans;
}
};

No comments:

Post a Comment