classSolution { public: boolspiral_edge(vector<vector<int> > &matrix, vector<int> &res, int curr_m, int curr_n, int start_i, int start_j) { int i = start_i, j = start_j; int cnt = 0, total = curr_m * curr_n;
if (curr_m <= 0 || curr_n <= 0) { returnfalse; } // 从(start_i,start_j)开始,长度为curr_m,curr_n for (i = start_i, j = start_j; j < start_j + curr_n; j++) { res.push_back(matrix[i][j]); cnt++; } if (cnt == total) { returntrue; } for (i = start_i + 1, j = start_j + curr_n - 1; i < start_i + curr_m - 1; i++) { res.push_back(matrix[i][j]); cnt++; } if (cnt == total) { returntrue; } for (i = start_i + curr_m - 1, j = start_j + curr_n - 1; j >= start_j; j--) { res.push_back(matrix[i][j]); cnt++; } if (cnt == total) { returntrue; } for (i = start_i + curr_m - 2, j = start_j; i > start_i; i--) { res.push_back(matrix[i][j]); cnt++; } returntrue; } vector<int> spiralOrder(vector<vector<int> > &matrix) { int m = matrix.size(); int n = matrix[0].size(); vector<int> res; int curr_m = m, curr_n = n; int start_i = 0, start_j = 0;
classSolution { public: vector<int> spiralOrder(vector<vector<int> > &matrix) { // 1 <= m, n <= 10 int i, j, m = matrix.size(), n = matrix[0].size(); vector<int> ret; int start_i = 0, start_j = 0;
while (m > 0 && n > 0) { if (start_j >= start_j + n) break; for (j = start_j; j < start_j + n; j++) ret.push_back(matrix[start_i][j]); j--;
if (start_i + 1 >= start_i + m) break; for (i = start_i + 1; i < start_i + m; i++) ret.push_back(matrix[i][j]); i--;
if (j - 1 < start_j) break; for (j = j - 1; j >= start_j; j--) ret.push_back(matrix[i][j]); j++;
if (i - 1 <= start_i) break; for (i = i - 1; i > start_i; i--) ret.push_back(matrix[i][j]); i++;