提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题过程
解题思路
按圈打印,打印完一圈后缩小圈再循环打印。
class Solution {
public int[] spiralOrder(int[][] matrix) {
if(matrix.length == 0 || matrix[0].length == 0){
return new int[0];
}
int row = matrix.length;
int col = matrix[0].length;
int left = 0;
int right = col - 1;
int top = 0;
int bottom = row - 1;
int [] res = new int[row * col];
int index = 0;
while(left <= right && top <= bottom){
//第一行
for(int i = left; i <= right; i++){
res[index++] = matrix[top][i];
}
for(int i = top + 1; i <= bottom; i++){
res[index++] = matrix[i][right];
}
if(left < right && top < bottom){
for(int i = right - 1; i > left; i--){
res[index++] = matrix[bottom][i];
}
for(int i = bottom; i > top; i--){
res[index++] = matrix[i][left];
}
}
left++;
right--;
top++;
bottom--;
}
return res;
}
}
总结
暂时没有总结,待续。。。