Another java solution


  • 0
    O
    public class Solution {
        public List<Integer> spiralOrder(int[][] matrix) {
            List<Integer> result = new ArrayList<Integer>();
            int m = matrix.length;
            if(m == 0) return result;
            int n = matrix[0].length;
            int i = 0;
            int j = 0;
            int layer = 0;
            while(result.size() < m*n){
                for(; j < n-layer; j++){
                    result.add(matrix[i][j]);
                }
                i++;
                j--;
                for(; i < m-layer && result.size() < m*n; i++){
                    result.add(matrix[i][j]);
                }
                i--;
                j--;
                for(; j >= layer && result.size() < m*n; j--){
                    result.add(matrix[i][j]);
                }
                j++;
                i--;
                for(; i > layer && result.size() < m*n; i--){
                    result.add(matrix[i][j]);
                }
                j++;
                i++;
                layer++;
                
            }
            return result;
        }
    }
    

Log in to reply
 

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