-
Notifications
You must be signed in to change notification settings - Fork 30
/
Spiral Matrix.cpp
45 lines (34 loc) · 1.1 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
38
39
40
41
42
43
44
45
/*
Solution by Rahul Surana
***********************************************************
Given an m x n matrix, return all elements of the matrix in spiral order.
***********************************************************
*/
#include <bits/stdc++.h>
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int c = matrix.size()*matrix[0].size(), i = 0, j = 0, il = 0,jl = 0;
vector<int> ans;
while(ans.size() < c){
while(j < matrix[0].size()-jl) ans.push_back(matrix[i][j++]);
i++;
j--;
if(ans.size() == c) break;
while(i < matrix.size()-il) ans.push_back(matrix[i++][j]);
j--;
i--;
if(ans.size() == c) break;
while(j >= jl) ans.push_back(matrix[i][j--]);
i--;
j++;
if(ans.size() == c) break;
while(i > il) ans.push_back(matrix[i--][j]);
j++;
il++;
jl++;
i = il;
}
return ans;
}
};