思路
从最外层开始用4个for循环,分别从左到右,从上到下,从右到左,最后从下到上打印。接着 x,y坐标都 +1开始递归调用,打印第二层,以此类推
下面测试4个不同行列的矩阵 5x5,4x4, 5x4, 4x5
public static void main(String[] args) {
int matrix0[][] =
{
{ 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 }
};
int matrix1[][] =
{
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 }
};
int matrix2[][] =
{
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 },
{ 17, 18, 19, 20 }
};
int matrix3[][] =
{
{ 1, 2, 3, 4, 5 },
{ 6, 7, 8, 9, 10 },
{ 11, 12, 13, 14, 15 },
{ 16, 17, 18, 19, 20 }
};
print(0, 0, matrix0);
print(0, 0, matrix1);
print(0, 0, matrix2);
print(0, 0, matrix3);
}
public static void print(int x, int y, int matrix[][]) {
int v = matrix.length;
int p = matrix[0].length;
if (x >= v / 2 && y >= p / 2) {
if (v % 2 != 0 && p % 2 != 0) {
System.out.print(matrix[x][y]);
}
System.out.println();// 换行
return;
}
for (int i = x; i < p - x; i++) {
System.out.print(matrix[y][i] + ",");
}
int q = p - x - 1;
for (int j = y + 1; j < v - y; j++) {
System.out.print(matrix[j][q] + ",");
}
int w = v - y - 1;
for (int k = q - 1; k >= x; k--) {
System.out.print(matrix[w][k] + ",");
}
for (int l = w - 1; l > y; l--) {
System.out.print(matrix[l][x] + ",");
}
print(++x, ++y, matrix);
}
打印结果为:
1,2,3,4,5,10,15,20,25,24,23,22,21,16,11,6,7,8,9,14,19,18,17,12,13
1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10,
1,2,3,4,8,12,16,20,19,18,17,13,9,5,6,7,11,15,14,10,
1,2,3,4,5,10,15,20,19,18,17,16,11,6,7,8,9,14,13,12