首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode 1030. Matrix Cells in Distance Order

Leetcode 1030. Matrix Cells in Distance Order

作者头像
Tyan
发布2021-09-06 15:39:02
5580
发布2021-09-06 15:39:02
举报
文章被收录于专栏:SnailTyanSnailTyan

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

1. Description

Matrix Cells in Distance Order
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/
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-08-27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. Description
  • 2. Solution
  • Reference
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档