2021.03.01油漆面积
题目描述
有n个矩形,依次给出其左下角坐标和右上角坐标x1,y1,x2,y2,求这些矩形重叠后的总面积。
输入格式
第一行,一个整数n,表示有多少个矩形(1<=n<10000)
接下来的n行,每行有4个整数x1 y1 x2 y2,空格分开,表示矩形的两个对角顶点坐标。
输出格式
一行一个整数,表示矩形覆盖的总面积面积。
数据规模和约定
(0<= x1,y1,x2,y2 <=10000)
思路
- 错误思路
将覆盖面积用一个最小矩形覆盖,得到minX,minY,maxX,maxY,在依次遍历这个矩形内的各个小方格在不在矩形中。 - 正确思路
用一个map数组记录小方格的计数情况,依次判断各个矩形。
代码
class Solution{
int minX=100001,minY=100001,maxX=0,maxY=0;
int n;
int x1,x2,y1,y2;
boolean[][] isCnt = new boolean[10001][10001]; //以防越界
void test() {
Scanner cin = new Scanner(System.in);
n = cin.nextInt();
int cnt = 0;
for(int i = 0; i < n; i++) {
x1=cin.nextInt();
y1=cin.nextInt();
x2=cin.nextInt();
y2=cin.nextInt();
for(int x = x1+1; x <= x2; x++) {
for(int y = y1+1; y <= y2; y++) {
if(!isCnt[x][y]) {
isCnt[x][y]=true;
cnt++;
}
}
}
}
System.out.println(cnt);
}
}