1. Description
Given a matrix of m*n elements, return all elements of the matrix in spiral order.
2. Solution
Just do it. In any loop, print the elements from left to right, top to down, right to left, and down to top.
Repeat the above process, until all elements have been printed.
3. Code
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int>ans;
int n = matrix.size();
if(n==0) return ans;
int m = matrix[0].size();
int k=0,count = n*m;
int t=0,b=n-1,l=0,r=m-1;
while(k<count){
for(int i = l;i<=r&&k<count;i++){
ans.push_back(matrix[t][i]);
k++;
}
t++;
for(int i=t;i<=b&&k<count;i++){
ans.push_back(matrix[i][r]);
k++;
}
r--;
for(int i=r;i>=l&&k<count;i--){
ans.push_back(matrix[b][i]);
k++;
}
b--;
for(int i = b;i>=t&&k<count;i--){
ans.push_back(matrix[i][l]);
k++;
}
l++;
}
return ans;
}
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int>ans;
int n = matrix.size();
if(n==0) return ans;
int m = matrix[0].size();
vector<vector<int>> vis(n, vector<int>(m,false));
int xx[4] = {0, 1, 0, -1};
int yy[4] = {1, 0, -1, 0};
int x = 0, y = 0, id = 0;
for(int i = 0; i < n * m; i++) {
ans.push_back(matrix[x][y]);
vis[x][y] = true;
int x1 = x + xx[id];
int y1 = y + yy[id];
if(x1>=0&&x1<n&&y1>=0&&y1<m&&vis[x1][y1]==false) {
x = x1;
y = y1;
continue;
} else {
id = (id + 1) % 4;
x += xx[id];
y += yy[id];
continue;
}
}
return ans;
}
};