525D Arthur and Walls(dfs+贪心)
Finally it is a day when Arthur has enough money for buying an apartment. He found a great option close to the center of the city with a nice price.
Plan of the apartment found by Arthur looks like a rectangle n × m consisting of squares of size 1 × 1. Each of those squares contains either a wall (such square is denoted by a symbol "*" on the plan) or a free space (such square is denoted on the plan by a symbol ".").
Room in an apartment is a maximal connected area consisting of free squares. Squares are considered adjacent if they share a common side.
The old Arthur dream is to live in an apartment where all rooms are rectangles. He asks you to calculate minimum number of walls you need to remove in order to achieve this goal. After removing a wall from a square it becomes a free square. While removing the walls it is possible that some rooms unite into a single one.
The first line of the input contains two integers n, m (1 ≤ n, m ≤ 2000) denoting the size of the Arthur apartments.
Following n lines each contain m symbols — the plan of the apartment.
If the cell is denoted by a symbol "*" then it contains a wall.
If the cell is denoted by a symbol "." then it this cell is free from walls and also this cell is contained in some of the rooms.
Output n rows each consisting of m symbols that show how the Arthur apartment plan should look like after deleting the minimum number of walls in order to make each room (maximum connected area free from walls) be a rectangle.
If there are several possible answers, output any of them.
5 5
.*.*.
*****
.*.*.
*****
.*.*.
.*.*.
*****
.*.*.
*****
.*.*.
6 7
***.*.*
..*.*.*
*.*.*.*
*.*.*.*
..*...*
*******
***...*
..*...*
..*...*
..*...*
..*...*
*******
4 5
.....
.....
..***
..*..
.....
.....
.....
.....
题意:给你一个n*m的格子,'.'代表空地,'*'代表墙,你使墙变为空地,问你最小的次数使每个空地块为矩形。
思路:每当搜索到有3个'.'的就让那个余下的变为空地,再次在它的四周8格以每4格搜索,直到都符合。
代码:
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 2005;
char mp[N][N];
int vis[N][N];
int n,m;
bool in(int x,int y)
{
if(x<0 || x>=n || y<0 || y>=m)return false;
return true;
}
bool check(int x,int y)
{
if(!in(x,y)|| mp[x][y]!='*')return false;
for(int i=-1; i<=0; i++)//这里-1~0就行,弄个搜索4格子的头
for(int j=-1; j<=0; j++)
{
int cnt = 0;
for(int k=0; k<2; k++)
for(int z=0; z<2; z++)
if(in(x+i+k,y+j+z) && mp[x+i+k][y+j+z] == '.')
cnt++;
if(cnt == 3)
return true;
}
return false;
}
void dfs(int x,int y)
{
if(check(x,y)&&!vis[x][y])
{
vis[x][y] = 1;
mp[x][y] = '.';
for(int i=-1; i<2; i++)
for(int j=-1; j<2; j++)
dfs(x+i,y+j);
}
}
int main()
{
//freopen("in.txt","r",stdin);
cin >> n >> m;
for(int i=0; i<n; i++)
scanf("%s",mp[i]);
for(int i=0; i<n; i++)
for(int j=0; j<m; j++)
dfs(i,j);
for(int i=0; i<n; i++)
puts(mp[i]);
return 0;
}