class Solution {
public:
vector<int> spiralOrder(vector<vector<int> > &matrix) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> sol;
if (matrix.size() == 0)
return sol;
if (matrix.size() == 1)
return matrix[0];
if (matrix[0].size() == 1) {
for (int k = 0; k < matrix.size(); k++)
sol.push_back(matrix[k][0]);
return sol;
}
int row = matrix.size();
int column = matrix[0].size();
int iter = 0, i = 0, j = 0;
while (iter < ((column/2))) {
while (j < column - iter - 1) {
sol.push_back(matrix[i][j]);
j++;
}
while (i < row - iter - 1) {
// j++;
sol.push_back(matrix[i][j]);
i++;
}
while (j > iter) {
// i++;
sol.push_back(matrix[i][j]);
j--;
}
while (i > iter) {
//j--;
sol.push_back(matrix[i][j]);
i--;
}
iter++;
i = iter;
j = iter;
if (sol.size() == row * column)
break;
}
// This loop is for filling the second last column in final loop.
while ((sol.size() != row * column)) {
sol.push_back(matrix[i][j]);
i++;
}
//sol.push_back(iter);
return sol;
}
};
No comments:
Post a Comment