题目:输入一个矩阵,按照从里向外的顺序依次打印出每一个数字。
代码:
1 #include <cstdio> 2 3 void PrintMatrixInCircle(int** numbers, int columns, int rows, int start); 4 void printNumber(int number); 5 6 void PrintMatrixClockwisely(int** numbers, int columns, int rows) 7 { 8 if (numbers == nullptr || columns <= 0 || rows <= 0) 9 return; 10 11 int start = 0; 12 13 while (columns > start * 2 && rows > start * 2) 14 { 15 PrintMatrixInCircle(numbers, columns, rows, start); 16 17 ++start; 18 } 19 } 20 21 void PrintMatrixInCircle(int** numbers, int columns, int rows, int start) 22 { 23 int endX = columns - 1 - start; 24 int endY = rows - 1 - start; 25 26 // 从左到右打印一行 27 for (int i = start; i <= endX; ++i) 28 { 29 int number = numbers[start][i]; 30 printNumber(number); 31 } 32 33 // 从上到下打印一列 34 if (start < endY) 35 { 36 for (int i = start + 1; i <= endY; ++i) 37 { 38 int number = numbers[i][endX]; 39 printNumber(number); 40 } 41 } 42 43 // 从右到左打印一行 44 if (start < endX && start < endY) 45 { 46 for (int i = endX - 1; i >= start; --i) 47 { 48 int number = numbers[endY][i]; 49 printNumber(number); 50 } 51 } 52 53 // 从下到上打印一行 54 if (start < endX && start < endY - 1) 55 { 56 for (int i = endY - 1; i >= start + 1; --i) 57 { 58 int number = numbers[i][start]; 59 printNumber(number); 60 } 61 } 62 } 63 64 void printNumber(int number) 65 { 66 printf("%d\t", number); 67 } 68 69 // ====================测试代码==================== 70 void Test(int columns, int rows) 71 { 72 printf("Test Begin: %d columns, %d rows.\n", columns, rows); 73 74 if (columns < 1 || rows < 1) 75 return; 76 77 int** numbers = new int*[rows]; 78 for (int i = 0; i < rows; ++i) 79 { 80 numbers[i] = new int[columns]; 81 for (int j = 0; j < columns; ++j) 82 { 83 numbers[i][j] = i * columns + j + 1; 84 } 85 } 86 87 PrintMatrixClockwisely(numbers, columns, rows); 88 printf("\n"); 89 90 for (int i = 0; i < rows; ++i) 91 delete[](int*)numbers[i]; 92 93 delete[] numbers; 94 } 95 96 int main(int argc, char* argv[]) 97 { 98 /* 99 1 100 */ 101 Test(1, 1); 102 103 /* 104 1 2 105 3 4 106 */ 107 Test(2, 2); 108 109 /* 110 1 2 3 4 111 5 6 7 8 112 9 10 11 12 113 13 14 15 16 114 */ 115 Test(4, 4); 116 117 /* 118 1 2 3 4 5 119 6 7 8 9 10 120 11 12 13 14 15 121 16 17 18 19 20 122 21 22 23 24 25 123 */ 124 Test(5, 5); 125 126 /* 127 1 128 2 129 3 130 4 131 5 132 */ 133 Test(1, 5); 134 135 /* 136 1 2 137 3 4 138 5 6 139 7 8 140 9 10 141 */ 142 Test(2, 5); 143 144 /* 145 1 2 3 146 4 5 6 147 7 8 9 148 10 11 12 149 13 14 15 150 */ 151 Test(3, 5); 152 153 /* 154 1 2 3 4 155 5 6 7 8 156 9 10 11 12 157 13 14 15 16 158 17 18 19 20 159 */ 160 Test(4, 5); 161 162 /* 163 1 2 3 4 5 164 */ 165 Test(5, 1); 166 167 /* 168 1 2 3 4 5 169 6 7 8 9 10 170 */ 171 Test(5, 2); 172 173 /* 174 1 2 3 4 5 175 6 7 8 9 10 176 11 12 13 14 15 177 */ 178 Test(5, 3); 179 180 /* 181 1 2 3 4 5 182 6 7 8 9 10 183 11 12 13 14 15 184 16 17 18 19 20 185 */ 186 Test(5, 4); 187 188 return 0; 189 }
时间: 2024-12-24 18:33:01