54. Spiral Matrix


DescriptionHintsSubmissionsDiscussSolution
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]


Layer by layer 
https://leetcode.com/problems/spiral-matrix/solution/



Xxxxxxxxx

r 1 = r2 , c1 < c 2class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        
        List<Integer> res = new ArrayList<>();
        if(matrix == null || matrix.length == 0) return res;
        // four vars : r1 = 0, r2 = matrix.length - 1 
        // c1 : 0, c2 = matrix[0].length - 1 
        // top : row is r1, col is from c1 to c2 
        // right : row is from r1 + 1 to r2,  col is  c2
        // bottom : row is r2, col is from c2 - 1 to c1 + 1
        // left : row is from r2 to r1 + 1, col is c1 
        
        // No need to print bottom if bottom is the same as top, when r1 = r2 
        // No need to print left when right is the same as left, when c1 = c2 
        int r1 = 0, r2 = matrix.length - 1;
        int c1 = 0, c2 = matrix[0].length - 1;
        while(r1 <= r2 && c1 <= c2){
            // is there a case when r1 <= r2 but c1 > c2 ??
            // top 
            for(int c = c1; c <= c2; c++){
                res.add(matrix[r1][c]);
            }
            // right
            for(int r = r1 + 1; r <= r2; r++){
                res.add(matrix[r][c2]);
            }
            // bottom only necessary when r1 < r2 ,  not r1 = r2 
            if(r1 < r2 && c1 < c2){
                for(int c = c2 - 1; c >= c1 + 1; c--){
                    res.add(matrix[r2][c]);
                }
                // left only ncecesaary when c1 < c2 , not c1 = c2
                for(int r = r2; r >= r1 + 1; r--){
                    res.add(matrix[r][c1]);
                }
            }
            r1++;
            c1++;
            r2--;
            c2--;
        }
        return res;   
    }
}
相關文章
相關標籤/搜索