54. Spiral Matrix (Medium)

https://leetcode.com/problems/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]

Solutions

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> ans =new ArrayList<>();

        if (matrix.length == 0) {
            return ans;
        }

        int row = matrix.length;
        int col = matrix[0].length;

        int m = Math.min(col, row);

        for (int i = 0; i < (int) Math.ceil(m / 2.0); i++) {
            List<Integer> tmp = spiralOrder(matrix, i);
            ans.addAll(tmp);
        }

        return ans;
    }

    private List<Integer> spiralOrder(int[][] matrix, int margin) {
        List<Integer> ans =new ArrayList<>();

        int row = matrix.length;
        int col = matrix[0].length;

        // Literally, following case will never matched, just for reuse purpose
        if (margin >= col || margin >= row) {
            return ans;
        }

        // Go through top row
        for (int i = margin; i < col - margin; i++) {
            ans.add(matrix[margin][i]);
        }

        // Go through right column
        for (int i = margin + 1; i < row - margin; i++) {
            ans.add(matrix[i][col - margin - 1]);
        }

        // Go through bottom row, in case the spiral only contains one row
        for (int i = col - margin - 2; i >= margin && (row - margin - 1 > margin); i--) {
            ans.add(matrix[row - margin - 1][i]);
        }

        // Go through left column, in case the spiral only contains one column
        for (int i = row - margin - 2; i > margin && (col - margin - 1 > margin); i--) {
            ans.add(matrix[i][margin]);
        }

        return ans;
    }
}

Incorrect Solutions

References

Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2019-12-03 11:01:17

results matching ""

    No results matching ""