-
Notifications
You must be signed in to change notification settings - Fork 0
/
L23-5.cpp
58 lines (47 loc) · 1.64 KB
/
L23-5.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
46
47
48
49
50
51
52
53
54
55
56
57
58
// Spiral Print
// LeetCode Question
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
vector<int> spiralOrder(vector<vector<int> >& matrix) {
vector<int> ans;
int row = matrix.size();
int col = matrix[0].size();
int count = 0;
int total = row*col;
//index initialisation
int startingRow = 0;
int startingCol = 0;
int endingRow = row-1;
int endingCol = col-1;
while(count < total) {
//print starting row
for(int index = startingCol; count < total && index<=endingCol; index++) {
ans.push_back(matrix[startingRow][index]);
count++;
}
startingRow++;
//print ending column
for(int index = startingRow; count < total && index<=endingRow; index++) {
ans.push_back(matrix[index][endingCol]);
count++;
}
endingCol--;
//print ending row
for(int index = endingCol; count < total && index>=startingCol; index--) {
ans.push_back(matrix[endingRow][index]);
count++;
}
endingRow--;
//print starting column
for(int index = endingRow; count < total && index>=startingRow; index--) {
ans.push_back(matrix[index][startingCol]);
count++;
}
startingCol++;
}
return ans;
}
};