• 按照环形顺序遍历:
  • 上侧遍历:从左往右,判断上标+1是否超出范围;
  • 右侧遍历:从上往下,判断右标-1是否超出范围;
  • 下侧遍历:从右往左,判断下标-1是否超出范围;
  • 左侧遍历:从上往下,判断左标+1是否超出范围。
class Solution {
public:
    vector<int> printMatrix(vector<vector<int> > matrix) {
        int m = matrix.size(), n = matrix[0].size();
        vector<int> result(m * n);
        int top = 0;
        int bottom = m - 1;
        int left = 0;
        int right = n - 1;
        int count = 0;
        while (1) {
            for (int i = left; i <= right; i++) {
                result[count++] = matrix[top][i];
            }
            if (++top > bottom) break;
            for (int i = top; i <= bottom; i++) {
                result[count++] = matrix[i][right];
            }
            if (--right < left) break;
            for (int i = right; i >= left; i--) {
                result[count++] = matrix[bottom][i];
            }
            if (--bottom < top) break;
            for (int i = bottom; i >= top; i--) {
                result[count++] = matrix[i][left];
            }
            if (++left > right) break;
        }
        return result;
    }
};