例如,如果輸入如下矩陣:
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 checkArray5;
/*輸入一個矩陣,按照從外向裏以順時針的順序依次打印出每一個數字,
例如,如果輸入如下矩陣:
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.*/
import java.util.ArrayList;
import java.util.List;
public class Test01 {
public static void main(String[] args) {
int[][] matrix = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
Solution solution=new Solution();
ArrayList<Integer> arrayList=solution.printMatrix(matrix);
System.out.println(arrayList);
}
}
class Solution {
public ArrayList<Integer> printMatrix(int[][] matrix) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < matrix[0].length; i++) {
// System.out.print(matrix[0][i]+",");//打印第上面的行
list.add(matrix[0][i]);
if (i == matrix[0].length - 1) {
for (int j = 1; j < matrix.length; j++) {
// System.out.print(matrix[matrix[0].length-1][j]+",");//打印最右邊的列
list.add(matrix[j][matrix[0].length - 1]);
if (j == matrix.length - 1) {
for (int k = matrix[0].length - 2; k >= 0; k--) {
// System.out.print(matrix[matrix.length-1][k]+",");//打印最下面的行
list.add(matrix[matrix.length - 1][k]);
if (k == 0) {
for (int z = matrix.length - 2; z > 0; z--) {
// System.out.print(matrix[0][z]+",");//打印最左邊的列
list.add(matrix[z][0]);
if(z==1) {
if(matrix.length>=3&&matrix[0].length>=3) {
int[][] temp=new int[matrix.length-2][matrix[0].length-2];
for(int e=1,g=0;e<matrix.length-1;e++) {//改造二維數組,將四邊刪除
for(int f=1,h=0;f<matrix[0].length-1;f++) {
temp[g][h]=matrix[e][f];
h++;
}
g++;
}
ArrayList<Integer> arrayList=printMatrix(temp);//要對返回的list進行合併
for(int r=0;r<arrayList.size();r++) {
list.add(arrayList.get(r));
}
}
}
}
}
}
}
}
}
}
return (ArrayList<Integer>) list;
}
}