class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
int n=matrix.length;
int m=matrix[0].length;
List<Integer> order = new ArrayList<Integer>();
boolean[][] visited=new boolean[n][m];
int row=0,col=0;
int flag=0;
for(int i=0;i<n*m;++i){
order.add(matrix[row][col]);
visited[row][col]=true;
if(flag==0){
if(col+1<m&&visited[row][col+1]==false){
++col;
}else{
++row;
flag=1;
}
}else if(flag==1){
if(row+1<n&&visited[row+1][col]==false){
++row;
}else{
--col;
flag=2;
}
}else if(flag==2){
if(col-1>=0&&visited[row][col-1]==false){
--col;
}else{
--row;
flag=3;
}
}else if(flag==3){
if(row-1>=0&&visited[row-1][col]==false){
--row;
}else{
++col;
flag=0;
}
}
}
return order;
}
}
用个额外矩阵作为标记确实是个好方法。