• [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 }
  • 相关阅读:
    关押罪犯
    文化之旅
    [USACO11OPEN]玉米田迷宫Corn Maze
    排队布局
    最短路计数
    【模板】单源最短路径(标准版)
    最短路径问题
    无向图最小环
    localStorage的使用
    移动端如何引入日期插件
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/10731217.html
Copyright © 2020-2023  润新知