java输出指定半径的圆的二维矩阵

小豆苗 1年前 ⋅ 1363 阅读

废话不多说,直接贴代码。正负坐标都支持。

    public static void main(String[] args) {
        drawCircleMatrix(new int[]{0, 0}, 10);
    }


    /**
     * 三维数组输出一个圆形坐标系
     * @param centerPos 中心点坐标
     * @param r 半径r 必须是正数
     */
    public static int[][][] drawCircleMatrix(int[] centerPos, int r) {
        if(r < 0) return null;

        int[] startPos = {centerPos[0] - r, centerPos[1] - r};
        int[] endPos = {centerPos[0] + r, centerPos[1] + r};

        int width = Math.abs(endPos[0] - startPos[0]) + 1;
        int height = Math.abs(endPos[1] - startPos[1]) + 1;
        int[][][] matrix = new int[width][height][2];
        int[][][] matrixResult = new int[width][height][1];
        for (int x = startPos[0]; x <= endPos[0]; x++) {
            for (int y = startPos[1]; y <= endPos[1]; y++) {
                int idxX = x - startPos[0];
                int idxY = y - startPos[1];

                matrix[idxX][idxY] = new int[]{x, y};

                int w = Math.abs(centerPos[0] - x);
                int h = Math.abs(centerPos[1] - y);
                double rr = Math.sqrt(w*w + h*h);
                rr = Math.abs(rr);
                if (rr <= r) {
                    matrixResult[idxX][idxY] = new int[]{1};
                } else {
                    matrixResult[idxX][idxY] = new int[]{0};
                }
            }
        }

        for(int i=0; i<matrix.length; i++) {
            for(int j=0; j<matrix[i].length; j++) {
                System.out.print(Arrays.toString(matrix[i][j]) + '\t');
            }
            System.out.println();
        }

        return matrix;
    }

没时间进一步优化了,有发现更优的方式,欢迎交流。


全部评论: 0

    我有话说: