剑指 Offer 29. 顺时针打印矩阵

54. 螺旋矩阵

题目描述

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

输入输出

1
2
3
4
5
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]

输入: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]

基本思路

矩阵 找好上下左右边界 注意:

  • res[x++] 等价于先给 res[x] 赋值,再给 x 自增 1 ;
  • ++t > b 等价于先给 t 自增 11 ,再判断 t > b 逻辑表达式。

java实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Solution {
public int[] spiralOrder(int[][] matrix) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
return new int[0];
}
int row = 0, column = 0, x = 0;
int rows = matrix.length - 1, columns = matrix[0].length - 1;
int[] res = new int[(rows + 1) * (columns + 1)];
while(true){
for(int i = column; i <= columns; i++) res[x++] = matrix[row][i];
if(++row > rows) break;
for(int i = row; i <= rows; i++) res[x++] = matrix[i][columns];
if(column > --columns) break;
for(int i = columns; i >= column; i--) res[x++] = matrix[rows][i];
if(row > --rows) break;
for(int i = rows; i >= row; i--) res[x++] = matrix[i][column];
if(++column > columns) break;
}
return res;
}
}

// 按照LeetCode-54的写法 按层模拟打印更好理解
class Solution {
public int[] spiralOrder(int[][] matrix) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return new int[0];
}
int rows = matrix.length, columns = matrix[0].length;
int[] res = new int[rows * columns];
int left = 0, right = columns - 1, top = 0, bottom = rows - 1, x = 0;
while(left <= right && top <= bottom){
for(int column = left; column <= right; column++){
res[x++] = matrix[top][column];
}
for(int row = top + 1; row <= bottom; row++){
res[x++] = matrix[row][right];
}
if(left < right && top < bottom){
for(int column = right - 1; column > left; column--){
res[x++] = matrix[bottom][column];
}
for(int row = bottom; row > top; row--){
res[x++] = matrix[row][left];
}
}
left++;right--;top++;bottom--;
}
return res;
}
}