题目:给定一个m x n大小的矩阵(m行,n列),按螺旋的顺序返回矩阵中的所有元素。
例如:输入:[[1,2,3],[4,5,6],[7,8,9]],输出:[1,2,3,6,9,8,7,4,5]
解答:
螺旋矩阵的思路:
定义上下左右四个方向
左方向的初始值就是二维数组的最左一列下标(left)
右方向的初始值就是二维数组的最右一列下标(right)
上方向的初始值就是二维数组的最上一行下标(top)
下方向的初始值就是二维数组的最下一行下标(bottom)
按照"右->下->左->上"的方向对二维数组进行填充,初始就是往右方向进行遍历,注意的是外层循环的条件就是左方向的值要小于等于右方向并且上方向的值要小于等于下方向
- 右方向遍历:for循环变量的初始值就是left,当达到right边界的时候,说明上面已经遍历完一行了,所以top++,准备向下遍历,需要将遍历的方向改为bottom;
- 下方向遍历:for循环变量的初始值就是top,当达到bottom边界的时候,说明右边已经遍历完一列了,所以right- -,准备向左遍历,需要将遍历的方向改为left;
- 左方向遍历:for循环变量的初始值就是right,当达到left边界的时候,说明下面已经遍历完一行了,所以bottom- -,准备向上遍历,需要将遍历的方向改为top;
- 上方向遍历:for循环变量的初始值就是bottom,当达到top边界的时候,说明左边已经遍历完一列了,所以left++,准备向右遍历,需要将遍历的方向改为right;
import java.util.*;
public class Solution {
public ArrayList<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> res = new ArrayList<Integer>();
if(matrix.length == 0 ) return res;
int top = 0;
int bottom = matrix.length - 1;//数组有多少行
int left = 0;
int right = matrix[0].length - 1;//数组有多少列
while(true) {
//top
for(int i = left; i <= right; i++){
res.add(matrix[top][i]); //从左往右填充第一行数据
}
top++;
if(left > right || top > bottom) break;
for(int i = top; i <= bottom; i++) {
res.add(matrix[i][right]);//从上到下遍历
}
right--;
if(left > right || top > bottom) break;
for(int i = right; i >= left; i--){
res.add(matrix[bottom][i]);
}
bottom--;
if(left > right || top > bottom) break;
for(int i = bottom; i >= top; i--){
res.add(matrix[i][left]);
}
left++;
if(left > right || top > bottom) break;
}
return res;
}
}