题意:给出一个n*m的地图,由‘*’和‘.’号组成,现在要将一些'.'改成'*'号使得所有局部的'.'号都能组成一个矩形,要保证修改的次数最少,最后输出改变后的矩形。
思路:最开始的思路是搜联通块,将联通块里面的'*'全部改成‘.’,但是题目范围较大,结果超时了。然后看到别人的是找一个基本元素块,n*m的矩形由这些元素块组成。发现:如果在一个2*2的方格内只有一个是‘*’那么就必须要将这个‘*’改成‘.’,这样bfs搜一遍即可。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <string>
#include <map>
#include <stack>
#include <vector>
#include <set>
#include <queue>
#pragma comment (linker,"/STACK:102400000,102400000")
#define maxn 2005
#define MAXN 2005
#define mod 1000000009
#define INF 0x3f3f3f3f
#define pi acos(-1.0)
#define eps 1e-6
#define lson rt<<1,l,mid
#define rson rt<<1|1,mid+1,r
#define FRE(i,a,b) for(i = a; i <= b; i++)
#define FREE(i,a,b) for(i = a; i >= b; i--)
#define FRL(i,a,b) for(i = a; i < b; i++)
#define FRLL(i,a,b) for(i = a; i > b; i--)
#define mem(t, v) memset ((t) , v, sizeof(t))
#define sf(n) scanf("%d", &n)
#define sff(a,b) scanf("%d %d", &a, &b)
#define sfff(a,b,c) scanf("%d %d %d", &a, &b, &c)
#define pf printf
#define DBG pf("Hi\n")
using namespace std;
typedef pair<int,int> pa;
int a[maxn][maxn];
char mp[maxn][maxn];
int n,m;
bool Isok(int x,int y)
{
if (x>=0&&x<n&&y>=0&&y<m)
return true;
return false;
}
bool num(int x,int y)
{
int s=a[x][y]+a[x+1][y]+a[x][y+1]+a[x+1][y+1];
if (s==3) return true;
return false;
}
bool change(int x,int y)
{
if (a[x][y]) return false;
if (num(x,y))
return true;
if (x-1>=0&&num(x-1,y))
return true;
if (y-1>=0&&num(x,y-1))
return true;
if (x-1>=0&&y-1>=0&&num(x-1,y-1))
return true;
return false;
}
void bfs()
{
int i,j;
queue<pa>Q;
while (!Q.empty()) Q.pop();
pa st,now;
FRL(i,0,n)
{
FRL(j,0,m)
{
if (change(i,j))
{
a[i][j]=1;
Q.push(make_pair(i,j));
}
}
}
while (!Q.empty())
{
st=Q.front(); Q.pop();
FRE(i,st.first-1,st.first+1)
{
FRE(j,st.second-1,st.second+1)
{
if (Isok(i,j)&&change(i,j))
{
a[i][j]=1;
Q.push(make_pair(i,j));
}
}
}
}
}
int main()
{
int i,j;
while (~sff(n,m))
{
FRL(i,0,n)
scanf("%s",mp[i]);
FRL(i,0,n)
{
FRL(j,0,m)
{
if (mp[i][j]=='*')
a[i][j]=0;
else
a[i][j]=1;
}
}
bfs();
FRL(i,0,n)
{
FRL(j,0,m)
{
if (a[i][j])
pf(".");
else
pf("*");
}
pf("\n");
}
}
return 0;
}
/*
5 5
*****
**.**
*.*.*
*...*
*****
*/