题目:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
例如:如果输入如下矩阵:
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。
第一种思路:
代码转自网络,楼主整理了一下:
void printMatrixInCircle(int matrix[5][5],unsigned int nRow,unsigned int nCol) { int upbound = 0, downbound = nRow - 1; int leftbound = 0, rightbound = nCol - 1; enum direction {right,down,left,up}; int row = 0, cloumn = 0; direction dir = right; while ( 1 ) { cout << matrix [row][cloumn] << " "; if ( upbound == downbound && leftbound == rightbound) break; switch ( dir ) { case right: if ( cloumn < rightbound ) { ++cloumn; } else if ( cloumn == rightbound ) { ++upbound; ++row; dir = down; } break; case down: if ( row < downbound ) ++row; else if ( row == downbound ) { --rightbound; --cloumn; dir = left; } break; case left: if ( leftbound < cloumn ) --cloumn; else if ( leftbound == cloumn ) { --downbound; --row; dir = up; } break; case up: if ( row > upbound ) --row; else if ( row == upbound ) { ++leftbound; ++cloumn; dir = right; } break; } } cout << endl; }
第二种思路:用递归:
思路是总打印第一行,然后创建新矩阵,新矩阵是把旧矩阵去掉第一行 然后逆时针旋转90度,递归
代码转自网络,楼主整理,部分修改:
void print( int** matrix, int num_of_rows, int num_of_cols) { for( int col = 0; col < num_of_cols ; col++ ) { cout << matrix[0][col] << " "; } if( num_of_rows > 1 ) { // using recursive function int newRows = num_of_cols ; int newCols = num_of_rows - 1; // create a new matrix int** newMatrix = new int*[newRows] ; for( int row = 0; row < newRows; row++ ) { newMatrix[row]=new int[newCols]; } for( int row = 0; row < newRows; row++ ) { for( int col = 0; col < newCols; col++ ) { newMatrix[row][col] = matrix[col+1][num_of_cols-row-1]; } } print( newMatrix, newRows, newCols ) ; for( int row = 0; row < newRows; row++ ) { delete [] newMatrix[row]; } delete [] newMatrix; } }
测试代码如下:
#include <iostream> using namespace std; void printMatrixInCircle(int matrix[5][5],unsigned int nRow,unsigned int nCol); void print( int** matrix, int num_of_rows, int num_of_cols); int main() { int matrix[5][5] = {{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15},{16,17,18,19,20},{21,22,23,24,25}}; printMatrixInCircle(matrix,5,5); int **tmp = new int *[5]; for (int i = 0; i != 5; ++i) { tmp[i] = new int[5]; } for (int i = 0; i != 5; ++i) { for (int j = 0; j != 5;++j) { tmp[i][j] = i*5 + j + 1; } } print(tmp,5,5); for (int i = 0; i != 5; ++i) { delete []tmp[i]; } delete []tmp; return 0; }