zoukankan      html  css  js  c++  java
  • 【蓝桥杯】算法训练 画图 Java语言

    问题描述
      在一个定义了直角坐标系的纸上,画一个(x1,y1)到(x2,y2)的矩形指将横坐标范围从x1到x2,纵坐标范围从y1到y2之间的区域涂上颜色。
      下图给出了一个画了两个矩形的例子。第一个矩形是(1,1) 到(4, 4),用绿色和紫色表示。第二个矩形是(2, 3)到(6, 5),用蓝色和紫色表示。图中,一共有15个单位的面积被涂上颜色,其中紫色部分被涂了两次,但在计算面积时只计算一次。在实际的涂色过程中,所有的矩形都涂成统一的颜色,图中显示不同颜色仅为说明方便。
    在这里插入图片描述
      给出所有要画的矩形,请问总共有多少个单位的面积被涂上颜色。
    输入格式
      输入的第一行包含一个整数n,表示要画的矩形的个数。
      接下来n行,每行4个非负整数,分别表示要画的矩形的左下角的横坐标与纵坐标,以及右上角的横坐标与纵坐标。
    输出格式
      输出一个整数,表示有多少个单位的面积被涂上颜色。
    样例输入
    2
    1 1 4 4
    2 3 6 5
    样例输出
    15
    评测用例规模与约定
      1<=n<=100,0<=横坐标、纵坐标<=100。

    思路
    录入数据

    static boolean[][] flag;
    	public static void main(String[] args) {
    		Scanner sc = new Scanner(System.in);
    		while (sc.hasNext()) {
    			flag = new boolean[100][100];
    			int n = sc.nextInt();sc.nextLine();
    			int[][] xy = new int[n][4];
    			for (int i = 0; i < xy.length; i++) {
    				for (int j = 0; j < xy[0].length; j++) {
    					xy[i][j] = sc.nextInt();
    				}
    				sc.nextLine();
    			}
    			for (int c = 0; c < xy.length; c++) {
    				paint(xy[c][0],xy[c][1],xy[c][2],xy[c][3]);
    			}
    			System.out.println(CountPaintRectangle());
    		}
    		sc.close();
    	}
    

    设置一个二维数组,往里面涂色。最后统计格子数

    开始我是以点来涂色的,然后检查时,如果该点的上面一点和右边一点都true的话,录入该点。但是这样的话,会多算格子。目前还没想清楚为啥

    flag = new boolean[100][100];
    
    private static void paint(int x1, int y1, int x2, int y2) {
    		for (int i = x1; i <= x2; i++) {
    			for (int j = y1; j <= y2; j++) {
    				flag[i][j] = true;
    			}
    		}
    	}
    	//判断矩阵是否被涂色
    	private static int CountPaintRectangle() {
    		int count = 0;
    		for (int i = 0; i < 100; i++) {
    			for (int j = 0; j < 100; j++) {
    				if(flag[i][j] == true &&flag[i+1][j] == true &&flag[i][j+1] == true)
    					count++;
    			}
    		}
    		return count;
    	}
    
    

    如果仅以记录左下坐标作为格子数,就是正确的

    //以左下角坐标作为方格数,右上角不算
    	private static void paint(int x1, int y1, int x2, int y2) {
    		for (int i = x1; i < x2; i++) {
    			for (int j = y1; j < y2; j++) {
    				flag[i][j] = true;
    			}
    		}
    	}
    	//判断矩阵是否被涂色
    	private static int CountPaintRectangle() {
    		int count = 0;
    		for (int i = 0; i < 100; i++) {
    			for (int j = 0; j < 100; j++) {
    				if(flag[i][j] == true)
    					count++;
    			}
    		}
    		return count;
    	}
    
    向好的方向走一步,就离坏的结果远一步
  • 相关阅读:
    HTML5结构
    HTML5新增的非主体元素header元素、footer元素、hgroup元素、adress元素
    CF GYM 100703G Game of numbers
    CF GYM 100703I Endeavor for perfection
    CF GYM 100703K Word order
    CF GYM 100703L Many questions
    CF GYM 100703M It's complicate
    HDU 5313 Bipartite Graph
    CF 560e Gerald and Giant Chess
    POJ 2479 Maximum sum
  • 原文地址:https://www.cnblogs.com/PersistLu/p/12748607.html
Copyright © 2011-2022 走看看