Menu Close

Matrix Cells in Distance Order….FTC

We are given a matrix with R rows and C columns has cells with integer coordinates (rCenter, cCenter), where 0 <= r < R and 0 <= c < C.
You are given four integers row, cols, rCenter, and cCenter. There is a rows x cols matrix and you are on the cell with the coordinates (rCenter, cCenter).

Return the coordinates of all cells in the matrix, sorted by their distance from (rCenter, cCenter) from the smallest distance to the largest distance. You may return the answer in any order that satisfies this condition.

The distance between two cells (r1, c1) and (r2, c2) is |r1 – r2| + |c1 – c2|.

Input: 
rows = 1, cols = 2, rCenter = 0, cCenter = 0

Output: [[0,0],[0,1]]
Explanation: The distances from (0, 0) to other cells are: [0,1]
def distOrder(rows,cols,rC,cC):
    d,L={},[]
    for i in range(rows):
        for j in range(cols):
            d[i,j]=abs(i-rC)+abs(j-cC)
    d=sorted(d.items(),key=lambda x:x[1])
    for i in d:
        L.append(list(i[0]))
    return L

rows=int(input('rows: '))
cols=int(input('cols: '))
rC=int(input('rC: '))
cC=int(input('cC: '))
print(distOrder(rows,cols,rC,cC))

 


INPUT_1:
rows: 1
cols: 2
rC: 0
cC: 0

OUTPUT:
[ [ 0, 0 ], [ 0, 1 ] ]


INPUT_2:
rows: 2
cols: 2
rC: 0
cC: 1

OUTPUT:
[ [ 0, 1 ], [ 0, 0 ], [ 1, 1 ], [ 1, 0 ] ]


INPUT_3:
rows: 2
cols: 3
rC: 1
cC: 2

OUTPUT:
[ [ 1, 2 ], [ 0, 2 ], [ 1, 1 ], [ 0, 1 ], [ 1, 0 ], [ 0, 0 ] ]


ILLUSTRATION:

Executed using python3