Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For 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]
.
/* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ public List<Integer> spiralOrder(int[][] matrix) { List<Integer> result = new ArrayList<>(); int m = matrix.length; if(m == 0) return result; int n = matrix[0].length; if(n == 0) return result; int k = 0, l = 0; while(k<m && l<n) { for(int i=l; i<n; i++) { result.add(matrix[k][i]); } k++; n--; for(int i=k; i<m; i++) { result.add(matrix[i][n]); } if(k < m) { m--; for(int i=n-1; i>=l; i--) { result.add(matrix[m][i]); } } if(l < n) { for(int i=m-1; i>=k; i--) { result.add(matrix[i][l]); } l++; } } return result; }