-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Description
- used array store the visited node,
- take care of the corner case when input like [[1],[2],[3],[4],[5],[6],[7],[8],[9]], m=9, n = 1, "no2","no4" loop may out of index
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int m = matrix.size();
int n = matrix[0].size();
bool used[m][n];
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
used[i][j] =false;
vector<int> ans(0);
for(int i = 0;i<m;i++) {
for(int j =i;j<n-i;j++) {
if (used[i][j]) break;
used[i][j] = true;
cout << "1==" << matrix[i][j] << endl;
ans.push_back(matrix[i][j]);
}
for(int j=i+1;j<m-i-1 && (n-i-1 >= 0) ;j++) {
if (used[j][n-i-1]) break;
used[j][n-i-1] = true;
cout << "2==" << matrix[j][n-i-1] << endl;
ans.push_back(matrix[j][n-i-1]);
}
for(int j =n-i-1;j>=i;j--) {
if (used[m-i-1][j]) break;
used[m-i-1][j] = true;
cout << "3==" << matrix[m-i-1][j] << endl;
ans.push_back(matrix[m-i-1][j]);
}
for(int j =m-i-2;j>=i+1 && (i < n);j--) {
if (used[j][i]) break;
used[j][i] =true;
cout << "4==" << matrix[j][i] << endl;
ans.push_back(matrix[j][i]);
}
}
return ans;
}
};
Metadata
Metadata
Assignees
Labels
No labels