则依次打印:1、2、3、4、8、12、16、15、14、13、9、5、6、7、11、10
思路:
① 递归打印,每次打印一圈
② 递归终止条件:设待打印圈的左上角坐标为(x,x),为:2*x >= columns || 2*x>= rows。columns和rows为矩阵的列与行数。推导思路:除最内圈(当为不完整的圈时),每圈将矩阵缩小两行两列。
③ 边界情况:若递归非终止,首先打印最上行。若当前圈至少两列,打印右列。若当前圈至少两列两行,打印下行。若当前圈至少三行两列,打印左列
编译环境:ArchLinux+Clang3.3,C++11
实现一:
#include <iostream> using namespace std; /** 顺时针打印矩阵 **/ void printMatrix(int **a, int columns, int rows, int start = 0) { if ( !a || columns<1 || rows<1 || start<0 ) return; if ( 2*start >= columns || 2*start >= rows ) return; int stopX = columns - 1 - start; int stopY = rows - 1 - start; for (int i = start; i <= stopX; i++) // 最上行 cout << a[start][i] << ' '; if (start < stopX) { // 最右列 for (int i = start+1; i <= stopY; i++) { cout << a[i][stopX] << ' '; } } if (start < stopX && start < stopY) { // 最下列 for (int i = stopX-1; i >= start; i--) { cout << a[stopY][i] << ' '; } } if (start < stopX && start < stopY-1) { // 最左列 for (int i = stopY-1; i >= start+1; i--) { cout << a[i][start] << ' '; } } printMatrix(a, columns, rows, start+1); // 打印邻接内圈 } int main() { int a[][4] = { {1,2,3,4}, {5,6,7,8}, {9,10,11,12}, {13,14,15,16}, }; int **b = new int*[4]; for (int i = 0; i < 4; i++) { b[i] = a[i]; } printMatrix(b, 4, 4); }