zoukankan      html  css  js  c++  java
  • [leetcode]54. Spiral Matrix螺旋矩阵

    Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

    Example 1:

    Input:
    [
     [ 1, 2, 3 ],
     [ 4, 5, 6 ],
     [ 7, 8, 9 ]
    ]
    Output: [1,2,3,6,9,8,7,4,5]

    Example 2:

    Input:
    [
      [1, 2, 3, 4],
      [5, 6, 7, 8],
      [9,10,11,12]
    ]
    Output: [1,2,3,4,8,12,11,10,9,5,6,7]

    题意:

    按螺旋方式遍历矩阵。

    Solution1: Simulation the process and implement it.

    code

     1 class Solution {
     2       public List<Integer> spiralOrder(int[][] matrix) {
     3         List<Integer> res = new ArrayList<>();
     4         if(matrix.length == 0 || matrix[0].length == 0) return res;
     5 
     6         int top = 0;
     7         int bottom = matrix.length-1;
     8         int left = 0;
     9         int right = matrix[0].length-1;
    10 
    11         while(true){
    12             for(int i = left; i <= right; i++) {
    13                 res.add(matrix[top][i]);
    14             }
    15             top++;
    16             if(left > right || top > bottom) break;
    17 
    18             for(int i = top; i <= bottom; i++) {
    19                 res.add(matrix[i][right]);
    20             }
    21             right--;
    22             if(left > right || top > bottom) break;
    23 
    24             for(int i = right; i >= left; i--) {
    25                 res.add(matrix[bottom][i]);
    26             }
    27             bottom--;
    28             if(left > right || top > bottom) break;
    29 
    30             for(int i = bottom; i >= top; i--){
    31                 res.add(matrix[i][left]);
    32             }
    33             left++;
    34             if(left > right || top > bottom) break;
    35         }
    36         return res;
    37     }
    38 }
  • 相关阅读:
    Java8-Stream-No.10
    Java8-Stream-No.09
    Java8-Stream-No.08
    Java8-Stream-No.07
    Java8-Stream-No.06
    Java8-Stream-No.05
    Java8-Stream-No.04
    Java8-Stream-No.03
    Java8-Stream-No.02
    Java8-Stream-No.01
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/10731217.html
Copyright © 2011-2022 走看看