题目描述
给定一个m x n大小的矩阵(m行,n列),按螺旋的顺序(顺时针)返回矩阵中的所有元素。
举例:
输入
[[1,2,3],[4,5,6],[7,8,9]]
输出
[1,2,3,6,9,8,7,4,5]
解题思路
数组模拟。顺时针打印,首先定义上下左右四个边界,每次遍历完一轮四个边界都要相应加1减1,每一轮遍历条件是上边界不超过下边界,左边界不超过右边界。要避免重复打印,在下、左遍历前要判断左右边界、上下边界。
Java实现
import java.util.*;
public class Solution {
public ArrayList<Integer> spiralOrder(int[][] matrix) {
//注意返回类型是ArrayList
ArrayList<Integer> res = new ArrayList<>();
//特殊情况判断,数组为空,直接返回空的res
if (matrix.length == 0) {
return res;
}
//定义上下左右边界
int top = 0, bottom = matrix.length - 1,
left = 0, right = matrix[0].length - 1;
//每一轮进行的条件是上边界不超过下边界,且左边界不超过右边界,每一轮顺序是上右下左
while (top <= bottom && left <= right) {
//从左到右遍历,执行完top加1
for (int i = left; i <= right; i++) {
res.add(matrix[top][i]);
}
top++;
//从上到下遍历,执行完right减1
for (int i = top; i <= bottom ; i++) {
res.add(matrix[i][right]);
}
right--;
if (top <= bottom) {
//从右到左遍历,执行完bottom减1
for (int i = right; i >= left ; i--) {
res.add(matrix[bottom][i]);
}
}
bottom--;
if (left <= right) {
//从下到上遍历,执行完left加1
for (int i = bottom; i >= top ; i--) {
res.add(matrix[i][left]);
}
}
left++;
}
return res;
}
}