public class test20{
public List<Integer> spiralOrder(int[][] matrix) {
List answer = new ArrayList();
if(matrix.length == 0)
return answer;
int rows = matrix.length;
int columns = matrix[0].length;
int[] d_rows = {0,1,0,-1};
int[] d_columns = {1,0,-1,0};
boolean[][] seen = new boolean[rows][columns];
int row=0, column=0, direct=0;
for(int i=0; i<rows*columns; i++){
answer.add(matrix[row][column]);
seen[row][column] = true;
int new_row = row+d_rows[direct];
int new_col = column+d_columns[direct];
if(new_row>=0 && new_row<rows && new_col>=0 && new_col<columns && !seen[new_row][new_col]){
row = new_row;
column = new_col;
}
else{
direct = (direct+1)%4;
row = row+d_rows[direct];
column = column+d_columns[direct];
}
}
return answer;
}
}