逆时针打印矩阵,输出结果如下图:
源代码如下:
#include<iostream> using namespace std; void PrintMatrixInCircle(int** matrix, int M, int N, int start); void printNumber(int number); //逆时针打印矩阵 void printMatrix(int M, int N, int** matrix) { if (matrix == NULL || M <= 0 || N <= 0) { return; } int start = 0; while (M>start*2&&N>start*2) { PrintMatrixInCircle(matrix, M, N, start); start++; } } //在圆圈中打印矩阵,打印一圈分4种情况:一步,二步,三步,四步 void PrintMatrixInCircle(int** matrix, int M, int N, int start) { int endX = M - 1 - start; int endY = N - 1 - start; //从上到下打印一列 for (int i = start; i <= endY; i++) { int number = matrix[i][start]; printNumber(number); } // 从左到右打印一行 if (start < endX) { for (int i = start + 1; i <= endX; i++) { int number = matrix[endY][i]; printNumber(number); } } // 从下到上打印一行 if (start < endX&&start < endY) { for (int i = endY - 1; i >= start; i--) { int number = matrix[i][endX]; printNumber(number); } } // 从右到左打印一行 if (start < endX-1 && start < endY) { for (int i = endX - 1; i >= start+1; i--) { int number = matrix[start][i]; printNumber(number); } } } //打印数字 void printNumber(int number) { cout<<number<<" "; } // ====================测试代码==================== void Test(int M, int N) { int i; cout << "Test Begin:" << M << " M," << N << " N." << endl; if (M < 1 || N < 1) { return; } int** matrix = new int*[N]; for ( i = 0; i < N; i++) { matrix[i] = new int[M]; for (int j = 0; j < M; j++) { matrix[i][j] = i * M + j + 1; } } printMatrix( M, N, matrix); cout << endl; for ( i = 0; i < N; ++i) delete[](int*)matrix[i]; delete[] matrix; } int main() { /* 1 */ Test(1, 1); /* 1 2 3 4 */ Test(2, 2); /* 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 */ Test(4, 4); /* 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 */ Test(5, 5); /* 1 2 3 4 5 */ Test(1, 5); /* 1 2 3 4 5 6 7 8 9 10 */ Test(2, 5); /* 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 */ Test(3, 5); /* 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 */ Test(4, 5); /* 1 2 3 4 5 */ Test(5, 1); /* 1 2 3 4 5 6 7 8 9 10 */ Test(5, 2); /* 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 */ Test(5, 3); /* 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 */ Test(5, 4); system("pause"); return 0; }
其实这个和顺时针打印的原理一样,在此不多赘述。如不明白,可以留言!我会补充