Leetcode 1030. Matrix Cells in Distance Order

本文介绍了两种Python实现方式,对给定矩阵中所有单元格按距离中心点的距离进行排序。第一种是直接根据距离排序,第二种则是采用广度优先搜索(BFS)策略。代码详细展示了这两种方法,并提供了LeetCode问题的链接作为参考。
摘要由CSDN通过智能技术生成

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Matrix Cells in Distance Order

2. Solution

**解析:**Version 1,直接根据距离进行排序。Version 使用广度优先搜索。

  • Version 1
class Solution:
    def allCellsDistOrder(self, rows: int, cols: int, rCenter: int, cCenter: int) -> List[List[int]]:
        coordinates = [[i, j] for i in range(rows) for j in range(cols)]
        coordinates.sort(key=lambda x: abs(x[0] - rCenter) + abs(x[1] - cCenter))
        return coordinates
  • Version 2
class Solution:
    def allCellsDistOrder(self, rows: int, cols: int, rCenter: int, cCenter: int) -> List[List[int]]:
        matrix = [[0] * cols for i in range(rows)]
        queue = collections.deque()
        queue.append((rCenter, cCenter))
        matrix[rCenter][cCenter] = 1
        coordinates = []
        while queue:
            x, y = queue.popleft()
            coordinates.append([x, y])
            matrix[x][y] = 1
            if x > 0 and matrix[x-1][y] == 0:
                matrix[x-1][y] = 1
                queue.append((x-1, y))             
            if x < rows - 1 and matrix[x+1][y] == 0:
                matrix[x+1][y] = 1
                queue.append((x+1, y))   
            if y > 0 and matrix[x][y-1] == 0:
                matrix[x][y-1] = 1
                queue.append((x, y-1))             
            if y < cols - 1 and matrix[x][y+1] == 0:
                matrix[x][y+1] = 1
                queue.append((x, y+1))   
        return coordinates

Reference

  1. https://leetcode.com/problems/matrix-cells-in-distance-order/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值