问题描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例 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]
问题解决
class Solution {
public int[] spiralOrder(int[][] matrix) {
if(matrix == null || matrix.length == 0) return new int[0];
int row = matrix.length, col = matrix[0].length;
int[] res = new int[row * col];
int left = 0, right = col - 1, top = 0, down = row - 1;
int index = 0;
while(left <= right && top <= down) {]
//从顶层,由左到右打印
for(int i = left; i <= right; i++) {
res[index++] = matrix[top][i];
}
top++;
if(left > right || top > down ) break;
//从右层,由上到下打印
for(int i = top; i <= down; i++) {
res[index++] = matrix[i][right];
}
right--;
if(left > right || top > down) break;
//从下层,由右到左打印
for(int i = right; i >= left; i--) {
res[index++] = matrix[down][i];
}
down--;
if(left > right || top >down) break;
//从左层,由下到上打印
for(int i = down; i >= top; i--) {
res[index++] = matrix[i][left];
}
left++;
}
return res;
}
}
来源:力扣
链接:https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/