程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

LeetCode-1030. Arrange matrix cells in distance order_ Python

編輯:Python
  • Given four integers row , cols , rCenter and cCenter . There is one rows x cols Matrix , Your coordinates on the cell are (rCenter, cCenter) .

  • Returns the coordinates of all cells in the matrix , And press and (rCenter, cCenter) From the smallest to the largest . You can return the answers in any order that meets this condition .

  • Cell (r1, c1) and (r2, c2) The distance between is |r1 - r2| + |c1 - c2|.

Example 1:

Input :rows = 1, cols = 2, rCenter = 0, cCenter = 0
Output :[[0,0],[0,1]]
explain : from (r0, c0) The distance to other cells is :[0,1]

Example 2:

Input :rows = 2, cols = 2, rCenter = 0, cCenter = 1
Output :[[0,1],[0,0],[1,1],[1,0]]
explain : from (r0, c0) The distance to other cells is :[0,1,1,2]
[[0,1],[1,1],[0,0],[1,0]] It will also be seen as the right answer .

Example 3:

Input :rows = 2, cols = 3, rCenter = 1, cCenter = 2
Output :[[1,2],[0,2],[1,1],[0,1],[1,0],[0,0]]
explain : from (r0, c0) The distance to other cells is :[0,1,1,2,2,3]
Other answers that meet the requirements of the questions will also be considered correct , for example [[1,2],[1,1],[0,2],[1,0],[0,1],[0,0]].

Tips :

1 <= rows, cols <= 100
0 <= rCenter < rows
0 <= cCenter < cols

Program code

class Solution:
def allCellsDistOrder(self, rows: int, cols: int, rCenter: int, cCenter: int) -> List[List[int]]:
ans = [[] for i in range(205)]
for i in range(rows):
for j in range(cols):
distance = abs(i - rCenter) + abs(j - cCenter)
ans[distance].append([i, j])
res = []
for i in ans:
if i:
res.extend(i)
return res

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved