Very straightforward java solution


  • 0
    Z
    public List<Integer> spiralOrder(int[][] matrix) {
        
        List<Integer> list = new ArrayList<Integer>();
        if (matrix == null || matrix.length == 0) return list;
        int x1 = 0, y1 = 0, x2 = matrix.length-1, y2 = matrix[0].length-1;
        
        while (x1 <= x2 && y1 <= y2) {
            
            //the top row
            for (int i = y1; i <= y2; ++i) list.add(matrix[x1][i]);
            
            //the right column
            for (int i = x1+1; i <= x2; ++i) list.add(matrix[i][y2]);
            
            //if the bottom row and the top row are the same row, then avoid
            //add twice
            if(x2 != x1)
                for (int i = y2-1; i >= y1; --i) list.add(matrix[x2][i]);
            
            //if the left and the right column are the same column, then avoid
            //add twice
            if(y1 != y2)    
                for (int i = x2-1; i >= x1+1; --i) list.add(matrix[i][y1]);
            x1++; x2--; y1++; y2--;
        }
        
        return list;
    }

Log in to reply
 

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