### Spiral Matrix

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].

``````import java.util.*;
/**
* Created by gzdaijie on 16/5/25
*/
public class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
if (matrix == null || matrix.length == 0) return new ArrayList<Integer>();
int m = matrix.length;
int n = matrix[0].length;

int[][] dirs = {{0, 1},{1, 0},{0, -1},{-1, 0}};
int top = 0, left = 0 ,right = n - 1, bottom = m - 1;
int k = m * n, dir = 0, x = 0, y = 0;

List<Integer> result = new ArrayList<>();
while (k-- > 0) {
if (dir == 0 && y >= right) {
top++;
dir = (dir + 1) % 4;
} else if (dir == 1 && x >= bottom) {
right--;
dir = (dir + 1) % 4;
} else if (dir == 2 && y <= left) {
bottom--;
dir = (dir + 1) % 4;
} else if (dir == 3 && x <= top) {
left++;
dir = (dir + 1) % 4;
}
x += dirs[dir][0];
y += dirs[dir][1];
}
return result;
}
}
``````
updated 2016-05-25 20:29:07