# Artwork

A template for an artwork is a white grid of n × m squares. The artwork will be created by painting q horizontal and vertical black strokes. A stroke starts from square (x1, y1), ends at square (x2, y2) (x1 = x2 or y1 = y2) and changes the color of all squares (x, y) to black where x1 ≤x≤x2 andy1 ≤y≤y2.

The beauty of an artwork is the number of regions in the grid. Each region consists of one ormore white squares that are connected to each other using a path of white squares in the grid,walking horizontally or vertically but not diagonally. The initial beauty of the artwork is 1. Yourtask is to calculate the beauty after each new stroke. Figure A.1 illustrates how the beauty of theartwork varies in Sample Input 1.

Input

The first line of input contains three integers n, m and q (1 ≤ n,m ≤ 1000, 1 ≤ q ≤ 104).Then follow q lines that describe the strokes. Each line consists of four integers x1, y1, x2

andy2 (1≤x1 ≤x2 ≤n,1≤y1 ≤y2 ≤m).Either x1 =x2 or y1 =y2 (or both).

Output

For each of the q strokes, output a line containing the beauty of the artwork after the stroke.

#### 样例输入

4 6 5
2 2 2 6
1 3 4 3
2 5 3 5
4 6 4 6
1 6 4 6

#### 样例输出

1
3
3
4
3思路：使用广度搜索。模拟题意为，通过输入的数据染对应方块的颜色为黑色，然后设定一个起点，上下左右递归遍历，如果存在白色块则把它染成别的颜色（不能是黑色了）。递归完成之后记得把颜色恢复成白色。我的代码：
import java.util.Scanner;

public class Main {
static Scanner scanner = new Scanner(System.in);
static int m = 0, n = 0, q = 0;
static int beauty = 0;

public static void main(String[] args) {
long t1=System.currentTimeMillis();
int x1, y1, x2, y2;
n = scanner.nextInt();//列
m = scanner.nextInt();//行
q = scanner.nextInt();
int[][] arr = new int[m + 2][n + 2];
for (int i = 0; i < n + 2; i++) {
arr[0][i] = 9;
arr[m + 1][i] = 9;
}
for (int i = 0; i < m + 2; i++) {
arr[i][0] = 9;
arr[i][n + 1] = 9;
}
for (int i = 0; i < q; i++) {
x1 = scanner.nextInt();
y1 = scanner.nextInt();
x2 = scanner.nextInt();
y2 = scanner.nextInt();
if (x1 == x2 && y1 == y2) {
arr[y1][x1] = 1;
} else if (x1 == x2) {
for (int j = y1; j <= y2; j++) {
arr[j][x1] = 1;
}
} else if (y1 == y2) {
for (int j = x1; j <= x2; j++) {
arr[y1][j] = 1;
}
}
System.out.println(cal(1, 1, arr));
for (int j = 0; j < m + 2; j++) {
for (int k = 0; k < n + 2; k++) {
if (arr[j][k] == -1) {
arr[j][k] = 0;
}
}
}
beauty = 0;
}
long t2=System.currentTimeMillis();
System.out.println(t2-t1+"ms");;
}

public static int cal(int x, int y, int[][] arr) {

//找到白块
for (int i = x; i < m + 1; i++) {
for (int j = y; j < n + 1; j++) {
if (arr[i][j] == 0) {//找到白块
//开始染色，把与白块相邻的都染色
arr[x][y]=-1;
stroke(i, j, arr);
beauty++;
}
}
}
return beauty;
}

public static void stroke(int x, int y, int[][] arr) {
//上右下左顺序

if (arr[x][y - 1] == 0) {
arr[x][y - 1] = -1;
stroke(x, y - 1, arr);
}
if (arr[x + 1][y] == 0) {
arr[x + 1][y] = -1;
stroke(x + 1, y, arr);
}
if (arr[x][y + 1] == 0) {
arr[x][y + 1] = -1;
stroke(x, y + 1, arr);
}
if (arr[x - 1][y] == 0) {
arr[x - 1][y] = -1;
stroke(x - 1, y, arr);
}

}
}

posted @ 2017-10-25 17:18  须小弥  阅读(592)  评论(0编辑  收藏  举报