题解 | #螺旋矩阵#
螺旋矩阵
http://www.nowcoder.com/practice/7edf70f2d29c4b599693dc3aaeea1d31
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> list = new ArrayList<Integer>();
//求m、n值
int m = matrix.length;
if (m == 0)
return list;
int n = matrix[0].length;
//设置数组的上、下、左、右值,随循环调整
int top = 0;
int bottom = m-1;
int left = 0;
int right = n-1;
//循环,采用螺旋方法读取,每次取完一行或一列数后对四个值操作并检查
while (top<=bottom && left<=right) {
for (int j = left; j<=right; j++) {
list.add(matrix[top][j]);
}
++top;
if (top>bottom)
break;
for (int i = top; i<=bottom; i++) {
list.add(matrix[i][right]);
}
--right;
if (left>right)
break;
for (int j = right; j>=left; j--) {
list.add(matrix[bottom][j]);
}
--bottom;
if (top>bottom)
break;
for (int i = bottom; i>=top; i--) {
list.add(matrix[i][left]);
}
++left;
if (left>right)
break;
}
return list;
}
}