Short Java solution


  • 0
    M

    Have a function that prints the outermost layer and just call it until you add every layer.

    public class Solution {
        public List<Integer> spiralOrder(int[][] matrix) {
            List<Integer> ans = new ArrayList<Integer>();
            if(matrix == null || matrix.length == 0) return ans;
            int R = matrix.length, C = matrix[0].length;
            
            for(int n = 0; n < Math.ceil(Math.min(R,C)/2.0); n++) {
                ans.addAll(outerMostOrder(matrix, n, n, C - 2*n, R - 2*n));
            }
            
            return ans;
        }
        
        private List<Integer> outerMostOrder(int[][] matrix, int r, int c, int width, int height) {
            int[] dr = new int[]{0, 1, 0, -1};
            int[] dc = new int[]{1, 0, -1, 0};
            List<Integer> ans = new ArrayList<Integer>();
            
            int mov = 0, i = r, j = c-1;
            while(ans.size() < width * height - ((Math.max(width-2,0))*(Math.max(height-2,0)))) {
                i = i + dr[mov];
                j = j + dc[mov];
                ans.add(matrix[i][j]);
                if(i + dr[mov] > r + height - 1 || j + dc[mov] > c + width - 1 || i + dr[mov] < r || j + dc[mov] < c) mov++;
            }
            
            return ans;
        }
    }
    

Log in to reply
 

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