LeetCode-54-螺旋矩阵


题意描述:

给定一个包含 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]

解题思路:
Alice: 这题面熟啊,我们是不是在哪见过 ?
Bob:PAT 那套题目做过啊。
Alice: 所以你还记得怎么写的吗 ?
Bob: 应该还记得。就是螺旋访问呗,假设有m行n列,先横着往右读取 m 个元素,在竖着往下 n-1 个元素,再横着往左读 m-1 个元素,再竖着往上读 n-2 的元素,然后重复这个步骤,一直到读完所有的元素。
Alice: 是这样吗 ?
在这里插入图片描述
Bob:就是就是。然后注意一下不要越界访问还有边界值输入的处理就好了。
Alice: 😎😎


代码:

Python 方法一:

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:

        if len(matrix) == 0 or len(matrix[0]) == 0:
            return []
        
        directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]
        i = 0
        j = -1
        m = len(matrix)
        n = len(matrix[0])
        cnt = 0
        tot = m * n
        ans = []
        index = -1
        
        
        while cnt < tot:
            #print('n ', n)
            index = (index + 1) % 4
            for x in range(n):
                i += directions[index][0]
                j += directions[index][1]
                ans.append(matrix[i][j])
                cnt += 1
            m -= 1

            index = (index + 1) % 4
            for x in range(m):
                i += directions[index][0]
                j += directions[index][1]
                ans.append(matrix[i][j])
                cnt += 1
            n -= 1        
        
        return ans

Java 方法一:

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {

        List<Integer> ans = new ArrayList();
        if(matrix.length == 0 || matrix[0].length == 0){
            return ans;
        }
        
        int rows = matrix.length;
        int cols = matrix[0].length;
        int i = 0;
        int j = -1;
        int cnt = 0;
        int tot = cols * rows;
        int[][] directions = {{0,1}, {1,0}, {0,-1}, {-1,0}};
        int index = -1;
        
        while(cnt < tot){
            
            index = (index + 1) % 4;
            for(int x=0; x<cols; ++x){
                i += directions[index][0];
                j += directions[index][1];
                ans.add(matrix[i][j]);
                cnt++;
            }
            rows--;

            index = (index + 1) % 4;
            for(int x=0; x<rows; ++x){
                i += directions[index][0];
                j += directions[index][1];
                ans.add(matrix[i][j]);
                cnt++;
            }
            cols--;
        }

        return ans;
    }
}

易错点:

  • 一些测试点:
[[1,2,3],[4,5,6],[7,8,9]]
[[1,2,3,4],[5,6,7,8]]
[[1],[2]]
[[1]]
[[2,3],[4,5]]
[[]]
[]
  • 答案:
[1,2,3,6,9,8,7,4,5]
[1,2,3,4,8,7,6,5]
[1,2]
[1]
[2,3,5,4]
[]
[]

总结:

在这里插入图片描述


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值