题目描述:
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字
class Solution { public: vector<int> spiralOrder(vector<vector<int> > &matrix) { vector<int> result; int nRows = matrix.size(); if (nRows == 0) return result; int nCols = matrix.at(0).size(); result.reserve(nRows * nCols); int startX = 0; int startY = 0; while (nRows > 2 * startX && nCols > 2 * startY) { PrintNumbers(matrix, startX, startY, result); ++startX; ++startY; } return result; } void PrintNumbers(vector<vector<int>>& matrix, int startX, int startY, vector<int>& result) { assert(startX >= 0 && startY >= 0); int nRows = matrix.size(); int nCols = matrix.at(0).size(); int rowLen = nRows - 2 * startX; // 当前矩形的长度 int colLen = nCols - 2 * startY; // 当前矩形的宽度 int endX = startX + colLen - 1; // endX - startX + 1 = colLen X为横坐标 int endY = startY + rowLen - 1; // endY - startY + 1 = rowLen Y为纵坐标 // 1. 从左往右 for (int i = startX; i <= endX; ++i) { result.push_back(matrix.at(startY).at(i)); } // 2. 从上往下 if (endY > startY) { for (int i = startY + 1; i <= endY; ++i) { result.push_back(matrix.at(i).at(endX)); } } // 3. 从右往左 if (endX > startX && endY > startY) { for (int i = endX - 1; i >= startX; --i) { result.push_back(matrix.at(endY).at(i)); } } // 4. 从下往上 if (endX > startX && endY > startY) { for (int i = endY - 1; i >= startY + 1; --i) { result.push_back(matrix.at(i).at(startX)); } } } };
具体分析详见我的博文:螺旋矩阵
剑指offer (20) 打印螺旋矩阵
时间: 2024-11-03 21:24:57