• [LC] 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]

    class Solution {
        public List<Integer> spiralOrder(int[][] matrix) {
            List<Integer> res = new ArrayList<>();
            if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) {
                return res;
            }
            int rowBegin = 0, rowEnd = matrix.length - 1;
            int colBegin = 0, colEnd = matrix[0].length - 1;
            
            while (rowBegin <= rowEnd && colBegin <= colEnd) {
                for (int i = colBegin; i <= colEnd; i++) {
                    res.add(matrix[rowBegin][i]);
                }
                rowBegin += 1;
                
                for (int i = rowBegin; i <= rowEnd; i++) {
                    res.add(matrix[i][colEnd]);
                }
                colEnd -= 1;
                
                if (rowBegin <= rowEnd) {
                    for(int i = colEnd; i >= colBegin; i--) {
                        res.add(matrix[rowEnd][i]);
                    }
                }
                rowEnd -= 1;
                
                if (colBegin <= colEnd) {
                    for (int i = rowEnd; i >= rowBegin; i--) {
                        res.add(matrix[i][colBegin]);
                    }
                }
                colBegin += 1;
            }
            return res;
        }
    }
  • 相关阅读:
    Gym 101194L / UVALive 7908
    POJ 2259
    POJ 2559
    Gym 101194E / UVALive 7901
    Gym 101194D / UVALive 7900
    一种整数集上二分的正确写法
    日常训练记录
    Gym 101194C / UVALive 7899
    Gym 101194A / UVALive 7897
    HDU 5542
  • 原文地址:https://www.cnblogs.com/xuanlu/p/11896345.html
Copyright © 2020-2023  润新知