本题就是一个需要多动手描下,没什么技术含量,但是需要比较细心的一个题
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
vector<int> printMatrix(vector<vector<int> > matrix) {
vector<int> ret;
if (matrix.size() == 0) {
return ret;
}
if (matrix[0].size() == 0) {
return ret;
}
// 记录待打印区域的左上角与右下角
int leftupx = 0, leftupy = 0, rightdownx = matrix[0].size() - 1, rightdowny = matrix.size() - 1;
while ((leftupx <= rightdownx) && (leftupy <= rightdowny)) {
for (int i = leftupx; i <= rightdownx; ++i) {
ret.push_back(matrix[leftupy][i]);
}
leftupy++;
if (leftupy > rightdowny) {
return ret;
}
for (int i = leftupy; i <= rightdowny; ++i) {
ret.push_back(matrix[i][rightdownx]);
}
rightdownx--;
if (leftupx > rightdownx) {
return ret;
}
for (int i = rightdownx; i >= leftupx; --i) {
ret.push_back(matrix[rightdowny][i]);
}
rightdowny--;
for (int i = rightdowny; i >= leftupy; --i) {
ret.push_back(matrix[i][leftupx]);
}
leftupx++;
}
return ret;
}