A33176. 俄罗斯方块问题描述小杨同学用不同种类的俄罗斯方块填满了一个大小为 n * m 的网格图。网格图由 n * m 个带颜色方块构成。小杨同学现在将这个网格图交给了你,请你计算出网格图中俄罗斯方块的种类数。如果两个同色方块是四连通(即上下左右四个相邻的位置)的,则称两个同色方块直接连通;若两个同色方块同时与另一个同色方块直接或间接连通,则称两个同色方块间接连通。一个俄罗斯方块由一个方块和所有与其直接或…
填空题
困难
知识点
题目描述
俄罗斯方块
问题描述
小杨同学用不同种类的俄罗斯方块填满了一个大小为 n * m 的网格图。
网格图由 n * m 个带颜色方块构成。小杨同学现在将这个网格图交给了你,请你计算出网格图中俄罗斯方块的种类数。
如果两个同色方块是四连通(即上下左右四个相邻的位置)的,则称两个同色方块直接连通;若两个同色方块同时与另一个同色方块直接或间接连通,则称两个同色方块间接连通。一个俄罗斯方块由一个方块和所有与其直接或间接连通的同色方块组成。定义两个俄罗斯方块的种类相同当且仅当通过平移其中一个俄罗斯方块可以和另一个俄罗斯方块重合;如果两个俄罗斯方块颜色不同,仍然视为同一种俄罗斯方块。
例如,在如下情况中,方块 和方块 是同一种俄罗斯方块,而方块1 和方块3 不是同一种俄罗斯方块。
方块1: 方块2: 方块3:
1 1 1 2 2 2 1
1 1 2 2 1 1
1 1输入格式
第一行包含两个正整数 n ,m ,表示网格图的大小。
对于之后 n 行,第 i 行包含 m 个正整数 ,a1, a2......., am表示该行 m 个方块的颜色。
输出格式
输出一个非负整数,表示俄罗斯方块的种类数。
样例1
输入
5 6
1 2 3 4 4 5
1 2 3 3 4 5
1 2 2 3 4 5
1 6 6 7 7 8
6 6 7 7 8 8输出
7参考答案
#include <cstdio>
#include <algorithm>
#include <map>
using namespace std;
const int N = 505;
int n, m;
int val[N][N];
int vis[N][N];
int xmin, xmax, ymin, ymax;
int posx[N * N], posy[N * N], cnt;
int idx[N * N];
bool isend[3 * N * N];
map <int, int> ch[3 * N * N];
int root, ncnt;
int ans;
void dfs(int x, int y, int c) {
if (x < 1 || x > n || y < 1 || y > m)
return;
if (vis[x][y])
return;
if (val[x][y] != c)
return;
vis[x][y] = 1;
xmin = min(xmin, x), xmax = max(xmax, x);
ymin = min(ymin, y), ymax = max(ymax, y);
posx[++cnt] = x;
posy[cnt] = y;
dfs(x - 1, y, c);
dfs(x + 1, y, c);
dfs(x, y - 1, c);
dfs(x, y + 1, c);
}
void go(int &n, int v) {
if (!ch[n].count(v))
ch[n][v] = ++ncnt;
n = ch[n][v];
return;
}
void work(int x, int y) {
cnt = 0;
xmin = n, xmax = 1;
ymin = m, ymax = 1;
dfs(x, y, val[x][y]);
for (int i = 1; i <= cnt; i++)
idx[i] = (posx[i] - xmin) * (ymax - ymin + 1) + (posy[i] - ymin);
sort(idx + 1, idx + cnt + 1);
int cur = root;
int lascnt = ncnt;
go(cur, xmax - xmin + 1);
go(cur, ymax - ymin + 1);
for (int i = 1; i <= cnt; i++)
go(cur, idx[i]);
ans += (! isend[cur]);
isend[cur] = 1;
}
int main() {
root = ++ncnt;
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
scanf("%d", &val[i][j]);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
if (!vis[i][j])
work(i, j);
printf("%d\n", ans);
return 0;
}
上一题
下一题