Spiral Order Matrix I

Given a matrix of m * n elements (m rows, n columns), return all elements of the matrix in spiral order.

Example:

Given the following matrix:

[
    [ 1, 2, 3 ],
    [ 4, 5, 6 ],
    [ 7, 8, 9 ]
]

You should return

[1, 2, 3, 6, 9, 8, 7, 4, 5]
public class Solution {
    public ArrayList<Integer> spiralOrder(List<ArrayList<Integer>> A) {
        ArrayList<Integer> ans=new ArrayList<>();
        int rowstart=0;
        int rowend=A.size()-1;
        int colstart=0;
        int colend=A.get(0).size()-1;
        int i=0;
        while(rowstart<=rowend && colstart<=colend){
            for (i = colstart; i <=colend; i++) { 
                ans.add(A.get(rowstart).get(i));
            } 
            rowstart++; 
  
            for (i = rowstart; i <= rowend; i++) { 
                ans.add(A.get(i).get(colend));
            } 
            colend--; 
  
            // Print the last row from the remaining rows */ 
            if (rowstart<=rowend) { 
                for (i = colend; i >= colstart; i--) { 
                    ans.add(A.get(rowend).get(i));
                } 
                rowend--; 
            } 
  
            // Print the first column from the remaining columns */ 
            if (colstart<=colend) { 
                for (i =rowend; i >= rowstart; i--) { 
                    ans.add(A.get(i).get(colstart));
                } 
                colstart++; 
            } 
        }
        return ans;
    }
}

Last updated