面试题18:顺时针打印矩阵
分析:把矩阵想象成若干个圈,用一个循环打印矩阵,每次打印矩阵的一个圈
#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; }
补充:软件开发 , C++ ,