美文网首页编程学习笔记
LeetCode 54. Spiral Matrix(螺旋矩阵

LeetCode 54. Spiral Matrix(螺旋矩阵

作者: 烛火的咆哮 | 来源:发表于2018-08-29 15:24 被阅读18次

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

示例 :

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

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

思路:

  • 本题难度较低,主要考验边界值处理,调bug容易调很久
  • 设定上下左右四个遍历方向,循环调用,直到遍历完整个矩阵
  • 本解法优先获取横向数据,次要获取纵向数据

代码:

    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new ArrayList<>();
        int lenh = matrix.length;
        if (lenh == 0)
            return res;
        int lenw = matrix[0].length;
        int i = 0, j = 0, wid = lenw, high = lenh, go = 0;

        while (res.size() < lenh * lenw) {
            // 对应左下右上四个方向
            switch (go) {
            //对于横向,全部扫描获取
            case 0:
                while (j < wid) {
                    res.add(matrix[i][j]);
                    j++;
                }
                j--;
                i++;
                go++;
                break;
            case 1:
                while (i < high - 1) {
                    res.add(matrix[i][j]);
                    i++;
                }
                go++;
                break;
            case 2:
                while (j >= lenw - wid) {
                    res.add(matrix[i][j]);
                    j--;
                }
                j++;
                i--;
                go++;
                high--;
                break;
            case 3:
                while (i > lenh - high) {
                    res.add(matrix[i][j]);
                    i--;
                }
                go = 0;
                wid--;
                break;
            }
        }
        return res;
    }

总结:

  1. 特别注意单行或单列时,是否能正确处理
  2. 本题是一个使用switch语句的好地方,好久没用到了
  3. 注意case语句添加break返回

相关文章

网友评论

    本文标题:LeetCode 54. Spiral Matrix(螺旋矩阵

    本文链接:https://www.haomeiwen.com/subject/icqkwftx.html