[코테 풀이] Matrix Cells in Distance Order

시내·2024년 7월 29일
0

Q_1030) Matrix Cells in Distance Order

출처 : https://leetcode.com/problems/matrix-cells-in-distance-order/

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|.

class Solution {
    
    public class CoorWithDist {
        int[] coordinates;
        int distance;

        public CoorWithDist(int[] coordinates, int distance) {
            this.coordinates = coordinates;
            this.distance = distance;
        }
    }

    public class DistOrder implements Comparator<CoorWithDist> {

        @Override
        public int compare(CoorWithDist o1, CoorWithDist o2) {
            return o1.distance - o2.distance;
        }
    }
    
    public int[][] allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) {
        int[][] answer = new int[rows * cols][2];
        int[][] all = allCoordinates(rows, cols);
        List<CoorWithDist> list = new ArrayList<>();
        for (int i = 0; i < all.length; i++) {
            int manDist = Math.abs(all[i][0] - rCenter) + Math.abs(all[i][1] - cCenter);
            list.add(new CoorWithDist(new int[]{all[i][0], all[i][1]}, manDist));
        }
        Collections.sort(list, new DistOrder());
        int answerIndex = 0;
        for (int l = 0; l < list.size(); l++) {
            answer[answerIndex++] = new int[]{list.get(l).coordinates[0], list.get(l).coordinates[1]};
        }
        return answer;
    }
    
    public int[][] allCoordinates(int rows, int cols) {
        int[][] all = new int[rows * cols][2];
        int index = 0;
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < cols; c++) {
                all[index++] = new int[]{r, c};
            }
        }
        return all;
    }
}
profile
contact 📨 ksw08215@gmail.com

0개의 댓글