Java实现LeetCode(54.螺旋矩阵)

时间:2022-04-15 18:06:12

LeetCode54. 螺旋矩阵 java实现

题目

  • 难度 中
  • 给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。

示例 1:

输入:

 [

  [ 1, 2, 3 ],

  [ 4, 5, 6 ],

  [ 7, 8, 9 ]

 ]

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

示例 2:

输入:

 [

   [1, 2, 3, 4],

   [5, 6, 7, 8],

   [9,10,11,12]

 ]

输出: [1,2,3,4,8,12,11,10,9,5,6,7]

思路

找出每个点的坐标,每个点每次延顺时针分别为右、下、左、上四个方向走一个位置,维护一个方向变量,不同方向时做相应的边界判断。每次遇到边界,必定改变方向,缩短原边界大小。

解法

?
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
public List<Integer> spiralOrder(int[][] matrix) {
        ArrayList<Integer> order = new ArrayList<>();
 
        if (matrix.length == 0 || matrix[0].length == 0) {
            return order;
        }
        int m = matrix.length;
        int n = matrix[0].length;
        int len = m * n;
        int row = 0;
        int col = 0;
        int leftMin = 0;
        //每次走上下左右四个方向,一次只走一格
        //注意点,因为是从(1,1)开始走的,所以上界最小row是第二行1
        int topMin = 1;
        //初始方向值
        int k = 0;
        int[][] dir = {
                {1, 0, -1, 0},
                {0, 1, 0, -1}
        };
        for (int i = 0; i < len; i++) {
            order.add(matrix[row][col]);
            col += dir[0][k % 4];
            row += dir[1][k % 4];
            switch (k % 4) {
                case 0:
                    //右
                    if (col > n - 1) {
                        col = n - 1;
                        row++;
                        k++;
                        n--;
                    }
                    break;
                case 1:
                    //下
                    if (row > m - 1) {
                        row = m - 1;
                        col--;
                        k++;
                        m--;
                    }
                    break;
                case 2:
                    //左
                    if (col < leftMin) {
                        col = leftMin;
                        leftMin++;
                        row--;
                        k++;
                    }
                    break;
                case 3:
                    //上
                    if (row < topMin) {
                        row = topMin;
 
                            topMin++;
 
                        col++;
                        k++;
                    }
                    break;
            }
 
 
        }
        return order;
    }

结果

2ms 战胜99.74%

到此这篇关于Java实现LeetCode(螺旋矩阵)的文章就介绍到这了,更多相关Java实现螺旋矩阵内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/qq_29777823/article/details/82357113