#include <vector> class Solution { public: vector<int> spiralOrder(vector<vector<int> > &matrix) { int m = matrix.size(); if (m == 0) { return {}; } int n = matrix[0].size(); if (n == 0) { return {}; } vector<int> res; res.reserve(m * n); int ub = 0, db = m - 1, lb = 0, rb = n - 1; while (res.size() < m * n) { if (ub <= db) { for (int j = lb; j <= rb; ++j) { res.push_back(matrix[ub][j]); } ++ub; } if (rb >= lb) { for (int i = ub; i <= db; ++i) { res.push_back(matrix[i][rb]); } --rb; } if (db >= ub) { for (int j = rb; j >= lb; --j) { res.push_back(matrix[db][j]); } --db; } if (lb <= rb) { for (int i = db; i >= ub; --i) { res.push_back(matrix[i][lb]); } ++lb; } } return res; } };
思路:维护四个边界,每次循环打印一圈边界上的值。