[面试题29. 顺时针打印矩阵]
难度 简单
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例 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]
限制:
0 <= matrix.length <= 100
0 <= matrix[i].length <= 100
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof
解法:
一圈圈的来打印矩阵,并用 startRow
、 startCol
、 endRow
、 endCol
分别来记录每一圈的开始行号 列号 和 结束行号 列号,然后每打印一圈行和列的起始位置 + 1,结束位置 - 1
例如下图:
第一圈为:1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5
第二圈为:6, 7, 11, 10
class Solution {
public int[] spiralOrder(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return new int[0];
}
int row = matrix.length; //行数
int col = matrix[0].length; //列数
int[] ans = new int[row * col];
int startRow = 0, startCol = 0;
int endRow = row - 1, endCol = col - 1;
int num = 0;
while(startRow <= endRow && startCol <= endCol){
for(int i = startCol; i <= endCol; i++){
ans[num++] = matrix[startRow][i];
}
for(int i = startRow + 1; i <= endRow; i++){
ans[num++] = matrix[i][endCol];
}
if(startRow != endRow) {
for(int i = endCol - 1; i >= startCol; i--){
ans[num++] = matrix[endRow][i];
}
}
if(startCol != endCol) {
for(int i = endRow - 1; i >= startRow + 1; i--){
ans[num++] = matrix[i][startCol];
}
}
//每转一圈, 行和列的起始位置 + 1,结束位置 - 1
startRow++; startCol++; endRow--; endCol--;
}
return ans;
}
}