螺旋矩阵
(牛客网—牛客题霸算法篇—NC38)
题目描述
给定一个m行n列大小的矩阵,按螺旋的顺序返回矩阵中的所有元素。
思路
Java实现
这道题目属于一道模拟题,只需要找出输出的规则和边界终止条件即可。
按时钟指针转动规则:
我们可以按照时钟中指针的转动方向来模拟这道题目的输出结果。
我们从最上面开始遍历,接着到边的时候就向下遍历,然后向左向上遍历,当一圈遍历结束的时候则进入里圈进行遍历。
代码实现
import java.util.*;
public class Solution {
public ArrayList<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> res = new ArrayList<>();
if(matrix.length == 0)
return res;
// 定义四个指针,并且充当边界限制的作用
int top = 0, bottom = matrix.length-1;
int left = 0, right = matrix[0].length-1;
while( top < (matrix.length+1)/2 && left < (matrix[0].length+1)/2 ){
//上面 左到右
for(int i = left; i <= right; i++){
res.add(matrix[top][i]);
}
//右边 上到下
for(int i = top+1; i <= bottom; i++){
res.add(matrix[i][right]);
}
//下面 右到左
for(int i = right-1; top!=bottom && i>=left; i--){
res.add(matrix[bottom][i]);
}
//左边 下到上
for(int i = bottom-1; left!=right && i>=top+1; i--){
res.add(matrix[i][left]);
}
// 遍历完一圈之后,所有往里面靠
++top;
--bottom;
++left;
--right;
}
return res;
}
}