Easy to Understand Java Solution (2ms)


  • 0
    S
    class Solution {
        public List<Integer> spiralOrder(int[][] matrix) {
            if (matrix.length == 0) {
                return new ArrayList<>();
            }
            int n = matrix.length;
            int m = matrix[0].length;
            List<Integer> res = new ArrayList<>();
            for (int i = 0; i < Math.min(m, n) / 2; i++) {
                for (int j = i; j < m - 1 - i; j++) {
                    res.add(matrix[i][j]);
                }
                for (int j = i; j < n - 1 - i; j++) {
                    res.add(matrix[j][m - 1 - i]);
                }
                for (int j = i; j < m - 1 - i; j++) {
                    res.add(matrix[n - 1 - i][m - 1 - j]);
                }
                for (int j = i; j < n - 1 - i; j++) {
                    res.add(matrix[n - 1 - j][i]);
                }
            }
            if (n >= m && m % 2 == 1) {
                int j = m / 2;
                for (int i = m / 2; i < n - m / 2; i++) {
                    res.add(matrix[i][j]);
                }
            } else if (n <= m && n % 2 == 1) {
                int i = n / 2;
                for (int j = n / 2; j < m - n / 2; j++) {
                    res.add(matrix[i][j]);
                }
            }
            
            return res;
        }
    }
    

Log in to reply
 

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