Simple Java Solution


  • 0
    S
    public class Solution {
        public List<Integer> spiralOrder(int[][] matrix) {
            if(matrix == null || matrix.length == 0) {
                return Collections.emptyList();
            }
            List<Integer> result = new ArrayList<>();
            int i1 = 0;
            int i2 = matrix.length - 1;
            int j1 = 0;
            int j2 = matrix[0].length - 1;
            while(i1 <= i2 && j1 <= j2) {
                result.addAll(spiralOrder(matrix, i1, i2, j1, j2));
                i1++;
                i2--;
                j1++;
                j2--;
            }
            return result;
            
        }
        
        private List<Integer> spiralOrder(int[][] matrix, int i1, int i2, int j1, int j2) {
            List<Integer> result = new ArrayList<>();
            for(int n = j1; n <= j2; n++) {
                result.add(matrix[i1][n]);
            }
            for(int m = i1+1; m <= i2; m++) {
                result.add(matrix[m][j2]);
            }
            for(int n = j2-1; n >= j1 && i2 != i1; n--) {
                result.add(matrix[i2][n]);
            }
            for(int m = i2-1; m >= i1+1 && j1 != j2; m--) {
                result.add(matrix[m][j1]);
            }
            return result;
        }
    }

Log in to reply
 

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