Share my concise java solution


  • 0
    N
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new ArrayList<>();
        int m = matrix.length;
        if(m == 0) return res;
        int n = matrix[0].length;
        
        int row = 0;
        int col = -1;
        while(true){
            for(int i = 0; i < n; i++){
                res.add(matrix[row][++col]);
            }
           
            if(--m == 0) break;
            for(int i = 0; i < m; i++){
                res.add(matrix[++row][col]);
            }
            if(--n == 0) break;
            for(int i = 0; i < n; i++){
                res.add(matrix[row][--col]);
            }
            if(--m == 0) break;
            for(int i = 0; i < m; i++){
                res.add(matrix[--row][col]);
            }
            if(--n == 0) break;
        }
        return res;
    }

Log in to reply
 

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