题目:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<map>
#include<queue>
#include<vector>
#include<string>
#include<fstream>
using namespace std;
typedef long long ll;
const int N = 2e3 + 105;
const int M = 1e6 + 5;
const int mod = 998244353;
const double Pi = acos(- 1.0);
const int INF = 0x3f3f3f3f;
const int G = 3, Gi = 332748118;
//
char mp[N][N];
int n, m;
bool visr[N], visc[N], visr2[N], visc2[N];
int root[N * N];
int Find(int x){
return x == root[x] ? x : root[x] = Find(root[x]);
}
void Union(int x, int y){
int tx = Find(x);
int ty = Find(y);
if(tx != ty){
root[ty] = tx;
}
}
int val(int x,int y){
return (x - 1) * m + y;
}
void solve()
{
for(int i = 1; i <= n * m; ++ i) root[i] = i;
for(int i = 1; i <= n; ++ i){
for(int j = 1; j <= m; ++ j){
if(mp[i][j] == '#'){
if(j < m &&mp[i][j + 1] == '#') Union(val(i,j), val(i,j + 1));
if(i < n && mp[i + 1][j] == '#') Union(val(i,j), val(i + 1, j));
}
}
}
int res = 0;
for(int i = 1; i <= n; ++ i){
for(int j = 1; j <= m; ++ j){
if(mp[i][j] == '#' && Find(val(i,j)) == val(i,j)){
res ++;
}
}
}
printf("%d
",res);
}
int main()
{
scanf("%d%d",&n,&m);
int B = 0, W = 0, flag = 0;
for(int i = 1; i <= n; ++ i){
B = 0, W = 0;
scanf("%s",mp[i]+1);
for(int j = 1; j <= m; ++ j){
if(mp[i][j] == '.') {
W = 1;
if(B) W = 2;
}
else if(mp[i][j] == '#'){
B = 1;
if(W == 2) flag = 1;
visr[i] = 1;
visc[j] = 1;
}
}
}
if(flag){
//cout<<"1"<<endl;
printf("-1
");
return 0;
}
B = 0, W = 0, flag = 0;
for(int j = 1; j <= m; ++ j){
B = 0, W = 0;
for(int i = 1; i <= n; ++ i){
if(mp[i][j] == '.'){
W = 1;
if(B) W = 2;
}
else if(mp[i][j] == '#'){
B = 1;
if(W == 2) flag = 1;
}
}
}
if(flag){
//cout<<"2"<<endl;
printf("-1
");
return 0;
}
for(int i = 1; i <= n; ++ i)
for(int j = 1; j <= m; ++ j){
if(!visr[i] && !visc[j]) {
//cout<<i<<" "<<j<<endl;
visr2[i] = 1;
visc2[j] = 1;
}
}
for(int i = 1; i <= n; ++ i)
if(!visr[i] && !visr2[i]) {
flag = 1;
}
for(int i = 1; i <= m; ++ i)
if(!visc[i] && !visc2[i]) {
flag = 1;
}
if(flag){
//cout<<"3"<<endl;
printf("-1
");
return 0;
}
solve();
return 0;
}
/*
3 7
......#
.......
#......
*/