思路:
先定义左上和右下角点坐标,打印可分为从左到右,从上到下,从右到左,从下到上。依次判断最后一圈的四个循环条件。
#include "../stdafx.h" #include <stdio.h> #include <stdlib.h> #include <vector> #include <iostream> using namespace std; vector<int> printMatrix(vector<vector<int> > matrix) { vector <int> res; int row = matrix.size(); // 行数 int col = matrix[0].size(); //列数 if (row == 0 || col == 0) return res; int left = 0, right = col - 1, top = 0, bottom = row - 1; while (left <= right&&top <= bottom){ //循环大条件 for (int i = left; i <= right; i++) res.push_back(matrix[top][i]); if (bottom-top >= 1){ //从上到下的打印条件 for (int i = top+1; i <= bottom; i++) res.push_back(matrix[i][right]); } if ((bottom - top >= 1 && (right - left >= 1))){ //右到左条件 for (int i = right- 1; i >= left; i--) res.push_back(matrix[bottom][i]); } if ((bottom - top >= 2 && (right - left >= 1))){ //下到上条件,注意for循环里i!=top for (int i = bottom - 1; i > top; i--) res.push_back(matrix[i][left]); } left++; right--; top++; bottom--; } return res; } int main(void){ vector<vector<int>> array = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, {13,14,15,16} }; vector<int>vec = printMatrix(array); vector <int>:: iterator it; for (it = vec.begin(); it != vec.end();it++) cout << *it << endl; getchar(); return 0; }