题目:
输入:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
输出:1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
package 多维数组与矩阵;
/**
* 输入:
*
* 1 2 3 4
* 5 6 7 8
* 9 10 11 12
* 13 14 15 16
* 输出:1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
*/
public class 顺时针打印二维数组 {
public static void main(String[] args) {
int[][] arr={
{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15,16},
};
f(arr);
}
static void f(int[][] arr) {
//定义左上角和右下角的下标
int leftUpRow = 0, leftUpCol = 0, rightDownRow = arr.length - 1, rightDownCol = arr[0].length - 1;
while (leftUpRow<=rightDownRow&&leftUpCol<=rightDownCol) {
int r = leftUpRow, c = leftUpCol;
//上面一条边
while (c <= rightDownCol) {
System.out.print(arr[r][c++] + " ");
}
//恢复
c = rightDownCol;
r++;
//右面一条边
while (r <= rightDownRow) {
System.out.print(arr[r++][c] + " ");
}
//恢复
r = rightDownRow;
c--;
//最下面一条边
while (c >= leftUpCol) {
System.out.print(arr[r][c--] + " ");
}
//恢复
c = leftUpCol;
r--;
//最左边一条边
while (r > leftUpRow) {
System.out.print(arr[r--][c] + " ");
}
leftUpRow++;
leftUpCol++;
rightDownRow--;
rightDownCol--;
}
}
}