1. 程式人生 > 其它 >29.順時針列印矩陣

29.順時針列印矩陣

技術標籤:演算法練習演算法

題目描述(劍指Offer29)

輸入一個矩陣,按照從外向裡以順時針的順序依次打印出每一個數字
例如,如果輸入如下4 X 4矩陣: 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 Jzof29 {
    public ArrayList<Integer> printMatrix(int [][] matrix) {
        ArrayList<Integer> list = new
ArrayList<Integer>(); //首先需要定義矩陣四個位置 int row1 = 0,row2 = matrix.length-1; int col1 = 0,col2 = matrix[0].length -1; while (row1 <= row2 && col1 <= col2){ //第一行 for (int i = col1; i <=col2 ; i++) { list.add(matrix[
row1][i]); } //右邊第一列 for (int i = row1+1; i <=row2 ; i++) { list.add(matrix[i][col2]); } //下面那一行,首先判斷有沒有下一行 if (row1 != row2){ for (int i = col2-1; i >= col1 ; i--) { list.add
(matrix[row2][i]); } } //左邊第一列,首先判斷有沒有這一列 if (col1 != col2){ for (int i = row2 - 1; i >= row1+1 ; i--) { list.add(matrix[i][col1]); } } row1++; row2--; col1++; col2--; } return list; } }