劍指Offer(書):順時針打印數組

題目:輸入一個矩陣,按照從外向裏以順時針的順序依次打印出每個數字,例如,若是輸入以下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.java

分析:書上的變量有點多,看不大懂,這裏藉助了一個輔助數組,用來斷定已經訪問過的節點。數組

package com.gjjun.jzoffer;import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 順時針打印矩陣
 *
 * @author gjjun
 * @date 2018/8/21
 **/
public class Solution29 {
    public static void main(String[] args) {
        int[][] arr = new int[2][4];
        int num = 1;
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 4; j++) {
                arr[i][j] = num;
                num++;
            }
        }
        System.out.println(Arrays.deepToString(arr));
        System.out.println(Arrays.toString(print(arr).toArray()));
    }

    public static ArrayList<Integer> print(int[][] array) {
        ArrayList<Integer> list = new ArrayList<>();
        if (array == null || array.length == 0) {
            return list;
        }
        int row = array.length;
        int col = array[0].length;
        int[][] temp = new int[row][col];
        temp[0][0] = 1;
        int i = 0;
        int j = 0;
        list.add(array[i][j]);
        int min = row > col ? col : row;
        min = (min & 1) == 1 ? min / 2 + 1 : min / 2;
        while (min-- > 0) {
            while (j < col - 1 && temp[i][j + 1] == 0) {
                list.add(array[i][j + 1]);
                temp[i][j + 1] = 1;
                j++;
            }
            while (i < row - 1 && temp[i + 1][j] == 0) {
                list.add(array[i + 1][j]);
                temp[i + 1][j] = 1;
                i++;
            }
            while (j > 0 && temp[i][j - 1] == 0) {
                list.add(array[i][j - 1]);
                temp[i][j - 1] = 1;
                j--;
            }
            while (i > 0 && temp[i - 1][j] == 0) {
                list.add(array[i - 1][j]);
                temp[i - 1][j] = 1;
                i--;
            }
        }
        return list;
    }
}
相關文章
相關標籤/搜索