17.顺时针打印矩阵

顺时针打印矩阵
  • 参与人数:3609时间限制:1秒空间限制:32768K
  • 本题知识点:  数组
  •  算法知识视频讲解

题目描述

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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的压值是通过vector.push_back(i)
// 16.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <vector>
using namespace::std;
class Solution {
public:
	vector<int> printMatrix(vector<vector<int> > vec) {
		int row = vec.size();
		int col = vec[0].size();

		int rowUp = 0;
		int rowDown = row - 1;
		int colLeft = 0;
		int colRight = col - 1;
		vector<int> retVec;
		int cursor = 0;

		if (row == 1 && col == 1){
			retVec.push_back(vec[0][0]);
			return retVec;
		}

		if (col == 1){
			for (int i = 0; i < row; i++){
				retVec.push_back(vec[i][0]);
			}
			return retVec;
		}

		if (row == 1){
			for (int i = 0; i < col; i++){
				retVec.push_back(vec[0][i]);
			}
			return retVec;
		}

		while (rowUp <= rowDown && colLeft <= colRight) {
			get(vec, retVec, cursor, rowUp, rowDown, colLeft, colRight);
		}
		return retVec;
	}

	void get(vector<vector<int> >& vec, vector<int>& retVec, int &cursor, int& rowUp, int& rowDown, int&colLeft, int& colRight) {
		printRowUp(vec, retVec, cursor, rowUp, colLeft, colRight);
		printColRigth(vec, retVec, cursor, rowUp, rowDown, colRight);
		printRowDown(vec, retVec, cursor, rowUp, rowDown, colRight, colLeft);
		printColLeft(vec, retVec, cursor, rowDown, rowUp, colLeft);
	}

	void printRowUp(vector<vector<int> >& vec, vector<int>& retVec, int& cursor, int& rowUp, int& colLeft, int& colRight) {
		for (int i = colLeft; i <= colRight; i++) {
			retVec.push_back(vec[rowUp][i]);
			cursor++;
		}
		rowUp++;
	}

	void printColRigth(vector<vector<int> >& vec, vector<int>& retVec, int& cursor, int& rowUp, int& rowDown, int& colRight) {
		for (int i = rowUp; i <= rowDown; i++) {
			retVec.push_back(vec[i][colRight]);
			cursor++;
		}
		colRight--;
	}

	void printRowDown(vector<vector<int> >& vec, vector<int>& retVec, int& cursor, int& rowUp, int& rowDown, int& colRight, int& colLeft) {
		if (rowUp <= rowDown){
			for (int i = colRight; i >= colLeft; i--) {
				retVec.push_back(vec[rowDown][i]);
				cursor++;
			}
			rowDown--;
		}
	}

	void printColLeft(vector<vector<int> >& vec, vector<int>& retVec, int& cursor, int& rowDown, int& rowUp, int& colLeft) {
		for (int i = rowDown; i >= rowUp; i--) {
			retVec.push_back(vec[i][colLeft] );
			cursor++;
		}
		colLeft++;
	}
};
int _tmain(int argc, _TCHAR* argv[])
{
	int row = 3;
	int col = 5;
	vector<vector<int> >vec;
	vec.resize(row);
	for (int i = 0; i<row; i++) vec[i].resize(col);

	int count = 1;
	for (int i = 0; i < row; i++){
		for (int j = 0; j < col; j++){
			vec[i][j] = count;
			count++;
		}
	}
	Solution s;
	vector<int>retVec = s.printMatrix(vec);
	return 0;
}

你可能感兴趣的:(17.顺时针打印矩阵)