/**
* 輸入一個矩陣,按照從外向裏以順時針的順序依次打印出每一個數字,
* 例如,如果輸入如下矩陣: 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 static void printMatrix() {
int[][] m = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16},
};
ArrayList<Integer> list = new ArrayList<>();
int x = m[0].length;//列 數
int y = m.length;//行 數
int left = 0;//左邊界,包含
int top = 0;//上邊界,包含
int right = x;//右邊界,不包含
int bottom = y;//下邊界,不包含
while (left <= right && top <= bottom) {
//打印上邊的行,行號是top,範圍是[0,bottom-1]
for (int j = left; j < right; j++) {
//行號不變,列號變,列號介於left與right之間
System.out.println("printMatrix--" + m[top][j]);
}
//打印右邊面的行,列號是right,範圍是[0,right-1]
for (int j = top + 1; j < bottom; j++) {
//列號不變,行號變,由於上面打印了右上角的元素,要排除這個元素,所以top+1
System.out.println("printMatrix--" + m[j][right - 1]);
}
//打印下邊的行
for (int j = right - 2; j >= left; j--) {
//行號不變,列號變,由於前面打印了右下角的元素,打印下邊元素時,排除這個元素,所以right-1-1
System.out.println("printMatrix--" + m[bottom - 1][j]);
}
//打印左邊的行
for (int j = bottom - 2; j > top; j--) {
//列號不變,行號變,由於左上角,左下角都已經打印了,需要排除這兩個元素,所以bottom-1-1,j>top
System.out.println("printMatrix--" + m[j][left]);
}
//打印了'第1圈',再打印'第2圈'
//top向下移動一行
top++;
//right向左移動一行
right--;
//bottom向上移動一行
bottom--;
//left向右移動一行
left++;
}
}
12-19 20:03:09.860 4162-4162/com.example.bxh.sayhello I/System.out: printMatrix--1
12-19 20:03:09.860 4162-4162/com.example.bxh.sayhello I/System.out: printMatrix--2
12-19 20:03:09.860 4162-4162/com.example.bxh.sayhello I/System.out: printMatrix--3
12-19 20:03:09.860 4162-4162/com.example.bxh.sayhello I/System.out: printMatrix--4
12-19 20:03:09.860 4162-4162/com.example.bxh.sayhello I/System.out: printMatrix--8
12-19 20:03:09.860 4162-4162/com.example.bxh.sayhello I/System.out: printMatrix--12
12-19 20:03:09.860 4162-4162/com.example.bxh.sayhello I/System.out: printMatrix--16
12-19 20:03:09.860 4162-4162/com.example.bxh.sayhello I/System.out: printMatrix--15
12-19 20:03:09.860 4162-4162/com.example.bxh.sayhello I/System.out: printMatrix--14
12-19 20:03:09.860 4162-4162/com.example.bxh.sayhello I/System.out: printMatrix--13
12-19 20:03:09.860 4162-4162/com.example.bxh.sayhello I/System.out: printMatrix--9
12-19 20:03:09.860 4162-4162/com.example.bxh.sayhello I/System.out: printMatrix--5
12-19 20:03:09.860 4162-4162/com.example.bxh.sayhello I/System.out: printMatrix--6
12-19 20:03:09.860 4162-4162/com.example.bxh.sayhello I/System.out: printMatrix--7
12-19 20:03:09.860 4162-4162/com.example.bxh.sayhello I/System.out: printMatrix--11
12-19 20:03:09.860 4162-4162/com.example.bxh.sayhello I/System.out: printMatrix--10