forked from codedecks-in/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Spiral-matrix.cpp
37 lines (34 loc) · 1.21 KB
/
Spiral-matrix.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
//Problem Number : 54
//Problem Name : Spiral Matrix
//Problem Statement : Given an m x n matrix, return all elements of the matrix in spiral order.
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int>res;
int left = 0, top = 0, down = matrix.size()-1, right = matrix[0].size()-1;
while(left <= right && top <= down){
//From left to right on top side
for(int i = left; i <= right; i++)
res.push_back(matrix[top][i]);
top++;
//From top to down on right side
for(int i = top; i <= down; i++)
res.push_back(matrix[i][right]);
right--;
if(top <= down){
//From right to left on down side
for(int i = right; i >= left; i--)
res.push_back(matrix[down][i]);
down--;
}
if(left <= right){
//From down to top on left side
for(int i = down; i >= top; i--)
res.push_back(matrix[i][left]);
left++;
}
}
return res;
}
};
//This code is contributed by Nikhil-1503