Sort matrix cells in distance order

It took a long time to understand the topic...

Insert picture description here



    public int[][] allCellsDistOrder(int R, int C, int r0, int c0) {
    
    
        // 存储距离
        int [] dis = new int[R*C];
        int [][] res = new int[R*C][2]; // 存储结果
        int [][] indexs = new int[R][C];
		
		// 下标
        int index = 0;
        for (int i = 0 ; i < R ; i++){
    
    
            for (int j = 0 ; j < C ; j++){
    
    
                indexs[i][j] = index++;
            }
        }
        // 计算距离
        for(int i = 0; i < R ; i++){
    
    
            for(int j = 0; j < C ; j++){
    
    
                // 距离
                dis[indexs[i][j]] = Math.abs(i - r0) + Math.abs(j - c0);
                // 距离坐标
                res[indexs[i][j]][0] = i;
                res[indexs[i][j]][1] =  j;
            }
        }

        // 插入排序
        for(int i = 0; i < R*C ; i++){
    
    
            int cnt = i;
            int temp = dis[i];
            for(int j = i + 1; j < R*C ; j++){
    
    
                if(temp > dis[j]){
    
    
                    temp = dis[j];
                    cnt = j;
                }
            }
            if(cnt != i){
    
    
                dis[cnt] = dis[i];
                dis[i] = temp;

                int[] t = res[i];
                res[i] = res[cnt];
                res[cnt] = t;
            }
        }
        return res;
    }


Guess you like

Origin blog.csdn.net/qq_43765535/article/details/107579652