# My cpp solution using same idea as rotate image

• ``````class Solution {
public:
vector<int> spiralOrder(vector<vector<int> > &matrix) {
vector<int> res;
int m = matrix.size();
if (m == 0)
return res;
int n = matrix[0].size();

int mm = m;
int nn = n;

int level = 0;
while (mm > 0 && nn > 0) {
int first = level;

if (mm == 1 && nn == 1) {
res.push_back(matrix[first][first]);
} else if (mm == 1) {
int horizon_last = n - 1 - first;
// top row
for (int i = first; i <= horizon_last; i++) {
res.push_back(matrix[first][i]);
}
} else if (nn == 1) {
int vertical_last = m - 1 - first;
int horizon_last = n - 1 - first;
// right
for (int i = first; i <= vertical_last; i++) {
res.push_back(matrix[i][horizon_last]);
}
} else {
int horizon_last = n - 1 - first;
// top row
for (int i = first; i < horizon_last; i++) {
res.push_back(matrix[first][i]);
}

int vertical_last = m - 1 - first;
// right
for (int i = first; i < vertical_last; i++) {
res.push_back(matrix[i][horizon_last]);
}

// bottom
for (int i = first; i < horizon_last; i++) {
int offset = i - first;
res.push_back(matrix[vertical_last][horizon_last - offset]);
}

// left
for (int i = first; i < vertical_last; i++) {
int offset = i - first;
res.push_back(matrix[vertical_last - offset][first]);
}
}

mm -= 2;
nn -= 2;
level++;
}

return res;
}
};``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.