[LeetCode Daily Question] [Simple] 1030. Arrange matrix cells in distance order

[LeetCode Daily Question] [Simple] 1030. Arrange matrix cells in distance order

1030. Arrange matrix cells in distance order

1030. Arrange matrix cells in distance order

Algorithm idea: array, sort

topic:

Insert picture description here

Ideas:

  1. Directly use Manhattan record sorting
  2. Divide buckets, and then connect them according to the bucket size

java code

Direct sort

class Solution {
    
    
    public int[][] allCellsDistOrder(int R, int C, int r0, int c0) {
    
    
		int[][] res = new int[R * C][2];//生成所有的矩阵坐标
		for (int i = 0; i < R; i++) {
    
    
			for (int j = 0; j < C; j++) {
    
    
				res[i * C + j][0] = i;
				res[i * C + j][1] = j;
			}
		}
        //利用曼哈顿距离直接排序
		Arrays.sort(res, new Comparator<int[]>() {
    
    
			public int compare(int[] o1, int[] o2) {
    
    
				return Math.abs(r0 - o1[0]) + Math.abs(c0 - o1[1]) - Math.abs(r0 - o2[0]) - Math.abs(c0 - o2[1]);
			}
		});
		return res;
    }
}

java code

Use buckets, divide buckets first, then connect

class Solution {
    
    
    //分桶,然后利用桶的大小实现排序(计数排序)
    public int[][] allCellsDistOrder(int R, int C, int r0, int c0) {
    
    
		int maxDis = Math.max(r0, R-1-r0) + Math.max(c0, C-1-c0);//最大曼哈顿距离
		List<int[]>[] bucket = new LinkedList[maxDis + 1];//桶
        
        //初始化桶
		for (int i = 0; i <= maxDis; i++) {
    
    
			bucket[i] = new LinkedList<int[]>();
		}

        //将矩阵所有下标按照曼哈顿距离分桶
		for (int i = 0; i < R; i++) {
    
    
			for (int j = 0; j < C; j++) {
    
    
				int dis = Math.abs(i - r0) + Math.abs(j - c0);
				bucket[dis].add(new int[]{
    
    i,j});
			}
		}

        //利用桶,按照曼哈顿距离生成最终答案
		int[][] res = new int[R * C][];
		int k = 0;
		for (int i = 0; i <= maxDis; i++) {
    
    
			for (int[] it : bucket[i]) {
    
    
				res[k++] = it;
			}
		}
		return res;
    }
}

Guess you like

Origin blog.csdn.net/qq_39457586/article/details/109743659