顺时针旋转打印矩阵元素

/*
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
例如:如果输入如下矩阵:

            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 <iomanip>
using namespace std;

int main(int argc, char** argv)
{
	if(argc < 2)
		return -1;
	int size = atoi(argv[1]);
	int* a = new int[size*size];

	for(int i = 0; i < size*size; ++i){
		a[i] = i;
	}
	for(int i = 0; i < size; ++i){
		for(int j=0; j < size; ++j){
			cout << setw(4) << a[i*size+j] << " ";
		}
		cout << endl;
	}
	cout << endl;

	int xs, ys, xe, ye, kc, kr;
	xs = 0;
	ys = 0;
	xe = size - 1;
	ye = size - 1;
	kc = ys;
	kr = xs;  // kr --> row  kc-->colume

	cout << " 旋转输出矩阵:\n";
	while(xs <= xe || ys <= ye ){
		if(kr == xs){
			for(kc = ys; kc<= ye; ++kc){  // 循环始行
				cout << a[kr*size+kc] << " ";
			}
			xs = xs+1; 
			kc = kc -1;
		}
		
		if(kc == ye){
			for(kr = xs; kr<= xe; ++kr){ // 循环末列
				cout <<a[kr*size+kc]  << " ";
			}
			ye = ye-1;
			kr = kr -1;
		}

		if(kr == xe){
			for(kc = ye ; kc>= ys; --kc){ // 循环末行
				cout << a[kr*size+kc] << " ";
			}
			xe = xe-1;
			kc = kc+1;
		}		

		if(kc == ys){
			for(kr = xe ; kr>= xs; --kr){ // 循环始列
				cout << a[kr*size+kc] << " ";
			}
			ys = ys+1;
			kr = kr +1;
		}
	}
}

你可能感兴趣的:(顺时针旋转打印矩阵元素)