【Leetcode】面试题29. 顺时针打印矩阵

 

 1 class Solution {
 2     public int[] spiralOrder(int[][] matrix) {
 3         if(matrix == null || matrix.length == 0){
 4             return new int[]{};
 5         }
 6         int index = 0;
 7         int l = 0, r = matrix[0].length-1, t = 0, b = matrix.length-1;
 8                 int[] ans = new int[(r+1) * (b+1)];
 9         while(true){
10             for(int i = l; i <= r; i++) ans[index++] = matrix[l][i];
11             if(++t > b) break;
12             for(int i = t; i <= b; i++) ans[index++] = matrix[i][r];
13             if(--r < l) break;
14             for(int i = r; i >= l; i--) ans[index++] = matrix[b][i];
15             if(--b < t) break;
16             for(int i = b; i >= t; i--) ans[index++] = matrix[i][l];
17             if(++l > r) break;
18         }
19         return ans;
20     }
21 }

 

posted @ 2020-05-31 16:18  xd会飞的猫  阅读(155)  评论(0编辑  收藏  举报