Buckle force - distance order of matrix cells

Given matrix R rows and C columns, where the cell is integer coordinates (r, c), satisfying 0 <= r <R and 0 <= c <C.

In addition, we give a cell coordinates (r0, c0) in the matrix.

Returns the coordinates of all cells in the matrix, according to (r0, c0) of the distance from the smallest to the largest arranged in order, wherein a distance between the two cell (r1, c1) and (r2, c2) Manhattan distance, | r1 - r2 | + | c1 - c2 |. (You can return any order to satisfy this condition answers.)

 

Example 1:

Input: R = 1, C 2 r0 0 c0 0 =, =, =
Output: [[0,0], [0,1]]
Dictionary : from (r0, c0) to the distance from other cells is: [0, 1]

example 2:

input: R = 2, C = 2 , r0 = 0, c0 = 1
output: [[0,1], [ 0,0], [1,1], [1,0]]
explanation: from (r0, c0) to the distance to other cells: [0,1,1,2]
[[0,1], [ 1,1], [0,0], [1,0]] will be treated as the correct answer.

Example 3:

Input: R = 2, C = 3 , r0 = 1, c0 = 2
Output: [[1,2], [0,2], [1,1], [0,1], [1, 0], [0,0]]
explanation: from (r0, c0) to the distance to other cells: [0,1,1,2,2,3]
other topics to meet the requirements will be regarded as correct answer , e.g. [[1,2], [1,1], [0,2], [1,0], [0,1], [0,0]].

 

prompt:

    . 1 <= R & lt <= 100
    . 1 <= C <= 100
    0 <= r0 of <R & lt
    0 <= cO <C

Source: stay button (LeetCode)
Link: https: //leetcode-cn.com/problems/matrix-cells -in-distance-order
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

 

 

class Solution {
    public int[][] allCellsDistOrder(int R, int C, int r0, int c0) {
        int[][] res = new int[R*C][2];
        int index = 0;
        for(int i = 0 ; i < R ; i ++)
            for(int j = 0 ; j < C ; j ++) {
                int[] xy = {i,j};
                res[index++] = xy;
            }
        Arrays.sort(res, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                int dis1 = Math.abs(o1[0]-r0)+Math.abs(o1[1]-c0);
                int dis2 = Math.abs(o2[0]-r0)+Math.abs(o2[1]-c0);
                return dis1 - dis2;
            }
        });
        return res;
    }
}

 

Guess you like

Origin www.cnblogs.com/JAYPARK/p/11267080.html