EASY JAVA SOLUTION with explaination


  • 1
    A

    Just go via the first row, last col, last row first col.
    Then, second row, second last col, second last row and second col.
    And keeping doing this until the list size is equal the total element number of matrix.

    public class Solution {

    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> re = new ArrayList<Integer>();
        if(matrix == null || matrix.length == 0) return re;
        int m = matrix.length;
        int n = matrix[0].length;
        int start = 0;
        int upRow = 0, boRow = m-1, leCol = 0, riCol = n-1;
        while(true){
            for(int i = start; i <= riCol; i++){
                re.add(matrix[upRow][i]);
            }
            if(re.size() == m*n) return re;
            start++;
            for(int i = start; i <= boRow; i++){
                re.add(matrix[i][riCol]);
            }
            if(re.size() == m*n) return re;
            for(int i = n - 1 - start; i >= leCol; i--){
                re.add(matrix[boRow][i]);
            }
            if(re.size() == m*n) return re;
            for(int i = m - 1 - start; i > upRow; i--){
                re.add(matrix[i][leCol]);
            }
            if(re.size() == m*n) return re;
            riCol--; boRow--; leCol++; upRow++;
        }
    }
    

    }


  • 0
    T

    Thanks. This is easy to understand.


  • 0
    A
    This post is deleted!

  • 0
    A

    @tracy_zh Thank you for replying!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.