问题描述:
You've gotten an n × m sheet of squared paper. Some of its squares are painted. Let's mark the set of all painted squares as A. Set A is connected. Your task is to find the minimum number of squares that we can delete from set A to make it not connected.
A set of painted squares is called connected, if for every two squares a and b from this set there is a sequence of squares from the set, beginning in a and ending in b, such that in this sequence any square, except for the last one, shares a common side with the square that follows next in the sequence. An empty set and a set consisting of exactly one square are connected by definition.
InputThe first input line contains two space-separated integers n and m (1 ≤ n, m ≤ 50) — the sizes of the sheet of paper.
Each of the next n lines contains m characters — the description of the sheet of paper: the j-th character of the i-th line equals either "#", if the corresponding square is painted (belongs to set A), or equals "." if the corresponding square is not painted (does not belong to set A). It is guaranteed that the set of all painted squares A is connected and isn't empty.
OutputOn the first line print the minimum number of squares that need to be deleted to make set A not connected. If it is impossible, print -1.
5 4 #### #..# #..# #..# ####
2
5 5 ##### #...# ##### #...# #####
2
题目分析:简单分析可以知道最多2个,因为我们完全可以分离角落的一个,使得不联通。关键是否能找到一个关键点(起到关键的连接作用),
例如
。。。。。。。。。。。
。。。。。。。。。。。
。。。# # # 。。。。。
。。。。# # # 。。。。这第二个点就关键点,把它删除了不联通
。。。。。# # 。。。。
。。。。。# 。。。。。
。。。# # # 。。。。。
。。。。# 。 # 。。。。
。。。。。# # 。。。。
。。。。。# 。。。。。
这样的点满足从它出发dfs,至少需要搜俩次以上才能搜完全图。
代码如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
using namespace std;
char G[55][55];
bool vis[55][55];
int Next[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
int n,m,ans;
void dfs(int x,int y)
{
int cnt=0;
vis[x][y]=true;
for (int i=0;i<4;i++) {
int dx=x+Next[i][0];
int dy=y+Next[i][1];
if (dx>=1&&dx<=n&&dy>=1&&dy<=m&&G[dx][dy]=='#') {
if (vis[dx][dy]==false) dfs(dx,dy);
}
}
}
bool check(int x,int y)
{
memset (vis,false,sizeof (vis));
vis[x][y]=true;
ans=0;
for (int i=0;i<4;i++) {
int dx=x+Next[i][0];
int dy=y+Next[i][1];
if (dx>=1&&dx<=n&&dy>=1&&dy<=m&&G[dx][dy]=='#'&&vis[dx][dy]==false) {
ans++;//记录需要几次
if (ans>=2) return true;//大于2,只需要删除它就够了
dfs(dx,dy);
}
}
return false;
}
int main()
{
scanf("%d%d",&n,&m);
for (int i=1;i<=n;i++) {
scanf("%s",G[i]+1);
}
memset (vis,false,sizeof (vis));
int num=0;
for (int i=1;i<=n;i++) {
for (int j=1;j<=m;j++) {
if (G[i][j]=='#') {
num++;
}
}
}
if (num<=2) {
printf("%d\n",-1);
return 0;
}
for (int i=1;i<=n;i++) {
for (int j=1;j<=m;j++) {
if (G[i][j]=='#') {
if (check(i,j)) {
printf("%d\n",1);
return 0;
}
}
}
}
printf("%d\n",2);
return 0;
}