Simple Java Solution!!!!


  • 0
    A
    public class Solution {
        public List<Integer> spiralOrder(int[][] matrix) {
            List<Integer> res = new ArrayList<Integer>();
            if (matrix == null || matrix.length == 0){
                return res;
            }
            int mEnd = matrix.length;
            int nEnd = matrix[0].length;
            int i = 0;
            int j = 0;
            int mStart = 0;
            int nStart = 0;
            while (mStart < mEnd && nStart < nEnd){
                while (j < nEnd){
                    res.add (matrix[i][j++]);
                }
                j--;
                i++;
                mStart++;
                while (i < mEnd){
                    res.add (matrix[i++][j]);
                }
                i--;
                j--;
                nEnd--;
                if (mStart < mEnd && nStart < nEnd){
                    while (j >= nStart){
                        res.add(matrix[i][j--]);
                    }
                    j++;
                    i--;
                    mEnd--;
                    while (i >= mStart){
                        res.add(matrix[i--][j]);
                    }
                    i++;
                    j++;
                    nStart++;
                }
            }
            return res;
        }
    }

Log in to reply
 

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