Analysis:Think of a matrix as several circles, and print a circle of the matrix with a loop.
# Include "stdafx. H "# include <iostream> using namespace STD; void printmatrixincircle (INT ** narr, int rows, int columns, int nstart) {int nendx = columns-1-nstart; int nendy = rows-1-nstart; // print a row from left to right (INT I = nstart; I <= nendx; I ++) {cout <narr [nstart] [I] <"" ;}// print a column from top to bottom if (nendy> nstart) {for (Int J = nstart + 1; j <= nendy; j ++) {cout <narr [J] [nendx] <"";}} // print a line from right to left if (nendy> nstart & nendx> nstart) {for (int t = nEndX-1; t> = nstart; t --) {cout <narr [nendy] [T] <";}}// print a column from bottom to top if (nendy-1> nstart & nendx> nstart) {for (INT n = nEndY-1; n> = nstart + 1; n --) {cout <narr [N] [nstart] <"";}}} // print the matrix clockwise. The number of rows is rows, and the number of columns is columnsvoid printmatrixclockwisely (INT ** narr, int rows, int columns) {If (narr = NULL | rows <= 0 | columns <= 0) {return;} int nstart = 0; while (rows> (nstart * 2) & columns> (nstart * 2) {printmatrixincircle (narr, rows, columns, nstart); nstart ++ ;}} int _ tmain (INT argc, _ tchar * argv []) {int nmatrix1 [4] [4] = {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}; int ** PP1 = new int * [4]; for (INT I = 0; I <4; I ++) {PP1 [I] = nmatrix1 [I];} printmatrixclockwisely (PP1, 4, 4); cout <Endl; int nmatrix2 [1] [4] = {1, 2, 3, 4}; int ** PP2 = new int * [1]; for (INT I = 0; I <1; I ++) {PP2 [I] = nmatrix2 [I];} printmatrixclockwisely (PP2, 1, 4); cout <Endl; int nmatrix3 [4] [1] = {1}, {2}, {3}, {4}; int ** PP3 = new int * [4]; for (INT I = 0; I <4; I ++) {PP3 [I] = nmatrix3 [I];} printmatrixclockwisely (PP3, 4, 1 ); cout <Endl; int nmatrix4 [2] [5] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int ** PP4 = new int * [2]; for (INT I = 0; I <2; I ++) {PP4 [I] = nmatrix4 [I];} printmatrixclockwisely (PP4, 2, 5 ); cout <Endl; System ("pause"); Return 0 ;}
Running result: