十四届蓝桥杯省赛Java B组 合并区域
就是将两个矩阵进行拼接,两矩阵可以旋转90 180 270 度。
因为数据比较小,所以这基本上就是一个大的枚举模拟加搜索,直接暴力求解。
import java.io.*;
import java.util.*;
public class Main{
static int n;
static int N = 101;
static int mod = (int)1e9 + 7;
static StreamTokenizer stt = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static int[][] f = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
// static int[][] ff = {{0, -1, 0}, {0, 0, 1}, {0, 1, 0}, {0, 0, -1}, {1, 0, 0}, {-1, 0, 0}};
// static int[] month = {0, 31,28,31,30,31,30,31,31,30,31,30,31};
static int[][] o = new int[N][N];
static int[][] p = new int[N][N];
static int[][] m = new int[3 * N][3 * N];
static int maxi;
private static int dfs(int x, int y) {
int k = 1;
m[x][y] = 0;
for(int i = 0; i < 4; i ++) {
int nx = x + f[i][0], ny = y + f[i][1];
if(nx < 1 || nx > 3 * n || ny < 1 || ny > 3 * n || m[nx][ny] == 0) continue;
k += dfs(nx, ny);
}
return k;
}
private static void draw(int bx, int by, int[][] o2) {
for(int i = bx, ii = 1; ii <= n; ii ++, i ++) {
for(int j = by, jj = 1; jj <= n; jj ++, j ++) {
m[i][j] = o2[ii][jj];
}
}
}
static void asd(int x, int y) throws IOException {
// 在地图上画o矩阵
draw(n + 1, n + 1, o);
// 在地图上画p矩阵
draw(x, y, p);
// 分别枚举o矩阵和p矩阵所有的1进行深搜
for(int i = 1; i <= n; i ++) {
for(int j = 1; j <= n; j ++) {
int nx = i + n, ny = j + n;
if(m[nx][ny] == 1)
maxi = Math.max(maxi, dfs(nx, ny));
}
}
for(int i = 1; i <= n; i ++) {
for(int j = 1; j <= n; j++) {
int nx = i + x - 1, ny = j + y - 1;
if(m[nx][ny] == 1)
maxi = Math.max(maxi, dfs(nx, ny));
}
}
}
private static void sov() throws IOException {
// 在一个三倍大的地图中,枚举p矩阵的坐上角顶点,默认o在中心的n阶矩阵位置
for(int i = 1; i <= 2 * n + 1; i ++) {
asd(1, i);
asd(2 * n + 1, i);
asd(i, 1);
asd(i, 2 * n + 1);
}
}
static void rotate() {
int[][] s = new int[N][N];
for(int i = 1; i <= n; i ++) {
for(int j = 1; j <= n; j ++) {
s[j][n - i + 1] = o[i][j];
}
}
for(int i = 1; i <= n; i ++) {
for(int j = 1; j <= n; j ++) {
o[i][j] = s[i][j];
}
}
}
static void sovle() throws Exception {
n = readInt();
for(int i = 1; i <= n; i ++) {
for(int j = 1; j <= n; j ++) {
o[i][j] = readInt();
}
}
for(int i = 1; i <= n; i ++) {
for(int j = 1; j <= n; j ++) {
p[i][j] = readInt();
}
}
maxi = 0;
// rotate();
// for(int i = 1; i <= n; i ++){
// for(int j = 1; j <= n; j ++) {
// bw.write(o[i][j] + " ");
// }
// bw.write("\n");
// }
for(int i = 0; i < 4; i ++) {
// 旋转o矩阵
rotate();
// 拼接两矩阵求解
sov();
}
bw.write(maxi + "\n");
}
public static void main(String args[]) throws Exception {
int t = 1;
// t = Integer.parseInt(br.readLine());
// t = readInt();
while((t --) > 0) {
// while((n = Integer.parseInt(br.readLine())) != 0) {
sovle();
}
bw.flush();
bw.close();
}
static int readInt() {
try {
stt.nextToken();
} catch (IOException e) {
e.printStackTrace();
}
return (int)stt.nval;
}
}