Below is my algorithm.:
public class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> res = new ArrayList<Integer>();
if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return res;
int row = matrix.length;
int col = matrix[0].length;
int end = row*col;
int m = 1,i = 0, j = 0, times = 0;
while(m <= end){
for(j = i; (j <= col - 1 - times) && ( m <= end) ; j++){ res.add(matrix[i][j]); m ++;} j--;
for(i++; i <= row - 1 - times && m <= end; i++){ res.add(matrix[i][j]); m ++;} i--;
for(j--; (j >= times) && (m <= end); j--){ res.add(matrix[i][j]); m ++;} j++;
for(i--; i >= times+1 && m <= end; i--){ res.add(matrix[i][j]); m ++;} i++;
times ++;
}
return res;
}
}