# Middle-题目111：54. 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].

Middle-题目29很像，在前面题基础上简单改一下代码即可。一个是读数组一个是写数组，所以读数组要使用一个visited[][]数组维护是否读过，而写数组只要判断是否为0即可。

public class Solution {
private  final int RIGHT = 1;
private  final int DOWN = 2;
private  final int LEFT = 3;
private  final int UP = 4;
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> list = new ArrayList<Integer>();
int row = matrix.length;
if(row==0)
return list;
int col = matrix[0].length;
boolean[][] visited = new boolean[row][col];
int count = 0,direction = RIGHT,i=0,j=0;
while (count < row * col) {
visited[i][j] = true;
switch (direction) {
case RIGHT:
if (j==col-1 || visited[i][j+1]) {
direction=DOWN;
i++;
}
else
j++;
break;
case DOWN:
if (i==row-1 || visited[i+1][j]) {
direction = LEFT;
j--;
}
else
i++;
break;
case LEFT:
if (j==0 || visited[i][j-1]) {
direction = UP;
i--;
}
else
j--;
break;
case UP:
if (visited[i-1][j]) {
direction = RIGHT;
j++;
}
else
i--;
break;
default:
break;
}
count++;
}
return list;
}
}

1ms,beats 3.18%,众数1ms,71.07%

• 本文已收录于以下专栏：

举报原因： 您举报文章：Middle-题目111：54. Spiral Matrix 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)