顺时针打印矩阵

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

示例 1:

输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]

示例 2:

输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]

算法流程:

空值处理: 当 matrix 为空时,直接返回空列表 [] 即可。

初始化: 矩阵 左、右、上、下 四个边界 l , r , t , b ,用于打印的结果列表 res 。

循环打印: “从左向右、从上向下、从右向左、从下向上” 四个方向循环,每个方向打印中做以下三件事 (各方向的具体信息见下表) ;

  根据边界打印,即将元素按顺序添加至列表 res 尾部;

  边界向内收缩 11 (代表已被打印);

  判断是否打印完毕(边界是否相遇),若打印完毕则跳出。 返回值: 返回 res 即可。

打印方向根据边界打印边界向内收缩是否打印完毕
从左向右 左边界l ,右边界 r 上边界 t 加 1 是否 t > b
从上向下 上边界 t ,下边界b 右边界 r 减 1 是否 l > r
从右向左 右边界 r ,左边界l 下边界 b 减 1 是否 t > b
从下向上 下边界 b ,上边界t 左边界 l 加 1 是否 l > r
 1  public int[] spiralOrder(int[][] matrix) {
 2         if(matrix.length==0){
 3             return new int[0];
 4         }
 5         int left = 0,right=matrix[0].length-1,top=0,bottom=matrix.length-1,count=0;
 6         int[] array = new int[(right+1)*(bottom+1)];
 7         while(true){
 8             //从左向右,top++
 9             for(int i = left;i<=right;i++){
10                 array[count++]=matrix[top][i];
11             }
12             if(++top>bottom) break;
13             //从上到下 ,right--
14             for(int i=top;i<=bottom;i++){
15                 array[count++]=matrix[i][right];
16             }
17             if(left>--right) break;
18 
19             //从右到左,bottom--
20             for(int i=right;i>=left;i--){
21                 array[count++]=matrix[bottom][i];
22             }
23             if(top>--bottom)break;
24 
25             //从下到上,left++
26             for(int i=bottom;i>=top;i--){
27                 array[count++]=matrix[i][left];
28             }
29             if(++left>right)break;
30         }
31         return array;
32     }

 

posted @ 2020-08-11 15:14  王余阳  阅读(224)  评论(0)    收藏  举报