1. 程式人生 > >劍指 Offer - 19:順時針列印矩陣

劍指 Offer - 19:順時針列印矩陣

題目描述

輸入一個矩陣,按照從外向裡以順時針的順序依次打印出每一個數字,例如,如果輸入如下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

題目連結:https://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a

// 模擬
public class Solution {
    public ArrayList<Integer> printMatrix
(int [][] matrix) { int left = 0; int right = matrix[0].length - 1; int top = 0; int bottom = matrix.length - 1; ArrayList<Integer> result = new ArrayList<>(); if (right < 0 || bottom < 0) return result; while (left <= right &&
top <= bottom) { for (int i = left; i <= right; i++) { result.add(matrix[top][i]); } for (int i = top+1; i <= bottom; i++) { result.add(matrix[i][right]); } if (top != bottom) { for (
int i = right-1; i >= left; i--) { result.add(matrix[bottom][i]); } } if (left != right) { for (int i = bottom-1; i >= top+1; i--) { result.add(matrix[i][left]); } } left++; right--; top++; bottom--; } return result; } }