一:题目
二:上码
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int n = matrix.size();
int m = matrix[0].size();
int loop = min(m/2,n/2);
int border = 1;
int startx = 0,starty = 0;
int i,j;
vector<int> ans;
while(loop--) {
i = startx;
j = starty;
for ( ; j < m - border; j++) {
ans.push_back(matrix[i][j]);
}
for ( ; i < n - border; i++) {
ans.push_back(matrix[i][j]);
}
for ( ; j > starty; j--) {
ans.push_back(matrix[i][j]);
}
for ( ; i > startx; i--) {
ans.push_back(matrix[i][j]);
}
startx++;
starty++;
border++;
}
if (n > m && m % 2 != 0) {
for ( ; startx < n - border +1; startx++) ans.push_back(matrix[startx][starty]);
} else if (n < m && n % 2 != 0) {
for ( ; starty < m - border+1; starty++) ans.push_back(matrix[startx][starty]);
} else if (m == n && m % 2 != 0) {
int mid = m/2;
ans.push_back(matrix[mid][mid]);
}
return ans;
}
};
|