题目:给定一个数组,将该数组从第一个元素开始顺时针打印出来。
分析:先考虑打印周围一圈的问题,然后可以使用递归求解,直到最后全都打印完为止。也就是先打印最外围的数,然后对于元二维数组中间的数组作为一个新的数组,重新打印该新数组的外围的数,直到最后全部打印完为止。
代码如下:
package problem2;
/**
* @author Hutongling
*/
public class 顺时针打印二维数组 {
static void print2DArray(int data[][]) {
if (data[0].length == 1) {
for (int i = 0; i < data.length; i++)
System.out.print(data[i][0] + " ");
return;
} else if (data.length == 1 && data[0].length != 1) {
for (int i = 0; i < data[0].length; i++)
System.out.print(data[0][i] + " ");
return;
} else if (data.length > 1) {
int row = data.length;
int column = data[0].length;
int i = 0;
for (i = 0; i < column; i++)
System.out.print(data[0][i] + " ");
for (i = 1; i < row; i++)
System.out.print(data[i][column - 1] + " ");
for (i = column - 2; i >= 0; i--)
System.out.print(data[row - 1][i] + " ");
for (i = row - 2; i >= 1; i--)
System.out.print(data[i][0] + " ");
if (row - 2 > 0 && column - 2 > 0) {
int subData[][] = new int[row - 2][column - 2];
for (i = 1; i < row - 1; i++)
for (int j = 1; j < column - 1; j++)
subData[i - 1][j - 1] = data[i][j];
data = null;
print2DArray(subData);
}
}
}
public static void main(String[] args) {
int data0[][] = {{1, 2, 3, 4, 5, 6 }};
int data[][] = { { 1, 2, 3, 4, 5, 6 }, { 2, 3, 4, 5, 6, 7 }, { 3, 4, 5, 6, 7, 8 }, { 4, 5, 6, 7, 8, 9 } };
int data1[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } };
int data2[][] = { { 1, 2, 3, 4, 5 }, { 2, 3, 4, 5, 6 }, { 3, 4, 5, 6, 7 }, { 4, 5, 6, 7, 8 }, { 5, 6, 7, 8, 9 } };
int data3[][]={{1},{2},{3},{4}};
print2DArray(data0);
System.out.println();
print2DArray(data);
System.out.println();
print2DArray(data1);
System.out.println();
print2DArray(data2);
System.out.println();
print2DArray(data3);
}
}
结果如下:
1 2 3 4 5 6
1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 3 4 5 6 7 6 5 4
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 3 4 5 6 7 6 5 4 5
1 2 3 4