分析:把矩陣想象成若干個圈,用一個循環打印矩陣,每次打印矩陣的一個圈
#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; //從左到右打印一行 for (int i=nStart; i<=nEndX; i++) { cout << nArr[nStart][i] << " "; } //從上到下打印一列 if (nEndY > nStart) { for (int j=nStart+1; j<=nEndY; j++) { cout << nArr[j][nEndX] << " "; } } //從右到左打印一行 if (nEndY > nStart && nEndX > nStart) { for (int t=nEndX-1; t>=nStart; t--) { cout << nArr[nEndY][t] << " "; } } //從下到上打印一列 if (nEndY -1 > nStart && nEndX > nStart) { for (int n=nEndY-1; n>=nStart+1; n--) { cout << nArr[n][nStart] << " "; } } } //順時針打印矩陣,行數為rows,列數為columns void 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; }