Leetcode 1030. Matrix Cells in Distance Order
Posted SnailTyan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 1030. Matrix Cells in Distance Order相关的知识,希望对你有一定的参考价值。
文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
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
以上是关于Leetcode 1030. Matrix Cells in Distance Order的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode --- 1030. Matrix Cells in Distance Order 解题报告
Leetcode 1030. Matrix Cells in Distance Order
Leetcode-1030 Next Greater Node In Linked List(链表中的下一个更大节点)