题目:
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
如:
输入矩阵: 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.
思路:
对于这类题,可使用"转圈"的方法从外向内遍历矩阵。
对于遍历到的每一圈,按照从左往右 从上往下 从右往左 从下往上的顺序 输出遍历到的元素。
贴代码:
#include <iostream> #include <vector> using namespace std; vector<int> printMatrix(vector<vector<int> > num) { int cols = num[0].size(); int rows = num.size(); int stRow = 0; int stCol = 0; int edRow = rows - 1; int edCol = cols - 1; vector<int> m; // 矩阵分圈 while(stRow <= edRow && stCol <= edCol) { //printEdge(matrix, res, stRow++, stCol++, edRow--, edCol--); // 只有一行 if(stRow == edRow) { for(int i = stCol; i <= edCol; ++i) { //cout<<m[stRow][i]<<" "; m.push_back(num[stRow][i]); } } // 只有一列 else if(stCol == edCol) { for(int i = stRow; i <= edRow; ++i) { //cout<<m[i][stCol]<<" "; m.push_back(num[i][stCol]); } } // 一般情况 else { int curRow = stRow; int curCol = stCol; // 遍历一行 while(curCol != edCol) { //cout<<m[curRow][curCol++]<<" ";// curRow = stRow m.push_back(num[stRow][curCol++]); } // 接着遍历一列 while(curRow != edRow) { //cout<<m[curRow++][curCol]<<" ";// curCol = edCol m.push_back(num[curRow++][edCol]); } // 又遍历一行 while(curCol != stCol) { //cout<<m[curRow][curCol--]<<" ";// curRow = edRow m.push_back(num[edRow][curCol--]); } // 又遍历一列 while(curRow != stRow) { //cout<<m[curRow--][curCol]<<" ";// curCol = stCol m.push_back(num[curRow--][stCol]); } } stRow++; edRow--; stCol++; edCol--; } return m; } int main(void) { vector<vector<int> > num(2, 2); vector<int> res; for (int i = 0; i < 2; ++i) { for (int j = 0; j < 2; ++j) { num[i][j] = i + j + 1; } } res = printMatrix(num); return 0; }