当前位置: 代码迷 >> 综合 >> CodeForces - 194C Cutting Figure (dfs)
  详细解决方案

CodeForces - 194C Cutting Figure (dfs)

热度:44   发布时间:2023-12-23 00:14:47.0

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.

Input

The 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.

Output

On 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.

Example
Input
5 4
####
#..#
#..#
#..#
####
Output
2
Input
5 5
#####
#...#
#####
#...#
#####
Output
2
Note

In the first sample you can delete any two squares that do not share a side. After that the set of painted squares is not connected anymore.

The note to the second sample is shown on the figure below. To the left there is a picture of the initial set of squares. To the right there is a set with deleted squares. The deleted squares are marked with crosses.


【题解】

 这道题看似没头绪,但其实不难,自己画几个图形就可以发现,任意图形,它最多有去掉两块格子就可以把它分成两部分,所以,我们可以从一个格子入手,遍历所有的格子,吧当前格子去掉,用dfs去找看看能不能把它分为两部分,直到所有的格子遍历完,如果存某一个格子去掉后就可以吧该图形分为两部分,则答案就是1,同时,如果一开始整个图形的格子数小于3个,那么就不存在答案,输出-1即可。

【AC代码】

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int m,n;
char str[55][55];
bool vis[55][55];
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};void dfs(int x,int y)
{vis[x][y]=1;for(int i=0;i<4;i++){int xx = x+dx[i];int yy = y+dy[i];if(xx>=0&&xx<m&&yy>=0&&yy<n&&str[xx][yy]=='#'&&vis[xx][yy]==0){dfs(xx,yy);}}
}int solve(int x,int y)
{int cnt=0;memset(vis,0,sizeof vis);vis[x][y]=1;for(int i=0;i<m;++i)for(int j=0;j<n;++j)if(str[i][j]=='#'&& !vis[i][j]){dfs(i,j);cnt++;}return cnt;
}int cal()
{for(int i=0;i<m;++i)for(int j=0;j<n;++j)if(str[i][j]=='#' && solve(i,j)>1)return 1;return 0;
}int main()
{while(~scanf("%d%d",&m,&n)){getchar();int ans=0;int s=100;for(int i=0;i<m;++i){for(int j=0;j<n;++j){scanf("%c",&str[i][j]);if(str[i][j]=='#')ans++;}getchar();}if(ans<3)printf("-1\n");else if(cal()){printf("1\n");}elseprintf("2\n");}return 0;
}