题解 | #螺旋矩阵#
螺旋矩阵
http://www.nowcoder.com/practice/7edf70f2d29c4b599693dc3aaeea1d31
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> res = new ArrayList<>();
if (matrix.length == 0) {
return res;
}
//定义边界
int low = 0, high = matrix.length - 1, left = 0, right = matrix[0].length - 1;
//定义游标
while (left <= right && low <= high) {//直到左右边界 和 上下边界重合为止
for (int i = left; i <= right; i++) {
res.add(matrix[low][i]);
}
low++;
if (low>high){
break;
}
for (int i = low; i <= high; i++) {
res.add(matrix[i][right]);
}
right--;
if(left>right){
break;
}
for ( int i = right; i >= left; i--) {
res.add(matrix[high][i]);
}
high--;
if(low>high){
break;
}
for (int i = high; i >= low; i--) {
res.add(matrix[i][left]);
}
left++;
if(left>right){
break;
}
}
return res;
}
}