Problem J: Color Circle
Time Limit: 1 Sec Memory Limit: 1280 MBSubmit: 212 Solved: 58
[ Submit][ Status][ Web Board]
Description
There are colorful flowers in the parterre in front of the door of college and form many beautiful patterns. Now, you want to find a circle consist of flowers with same color. What should be done ?
Assuming the flowers arranged as matrix in parterre, indicated by a N*M matrix. Every point in the matrix indicates the color of a flower. We use the same uppercase letter to represent the same kind of color. We think a sequence of points d1, d2, … dk makes up a circle while:
1. Every point is different.
2. k >= 4
3. All points belong to the same color.
4. For 1 <= i <= k-1, di is adjacent to di+1 and dk is adjacent to d1. ( Point x is adjacent to Point y while they have the common edge).
N, M <= 50. Judge if there is a circle in the given matrix.
Input
There are multiply test cases.
In each case, the first line are two integers n and m, the 2nd ~ n+1th lines is the given n*m matrix. Input m characters in per line.
Output
Output your answer as “Yes” or ”No” in one line for each case.
Sample Input
3 3
AAA
ABA
AAA
Sample Output
Yes
题目链接:http://acm.hzau.edu.cn/problem.php?cid=1029&pid=9
题目的意思就是问你地图上有没有一个圈,dfs一下就可以了,我记得以前做过这种题
代码:
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
int n,m,cnt;
char c[110][110];
int vis[110][110];
int dx[4]={1,-1,0,0};
int dy[4]={0,0,1,-1};
bool dfs(char s,int sx,int sy,int x,int y){
if(sx==x&&sy==y&&vis[sx][sy]){
return cnt>=4?true:false;
}
vis[x][y]=1;
for(int i=0;i<4;i++){
int tx=x+dx[i];
int ty=y+dy[i];
if(tx>=0&&tx<n&&ty>=0&&ty<m&&c[tx][ty]==s&&vis[tx][ty]==0||(tx==sx&&ty==sy)){
cnt++;
if(dfs(s,sx,sy,tx,ty))
return true;
cnt--;
}
}
return false;
}
bool solve(){
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
memset(vis,0,sizeof(vis));
cnt=0;
if(dfs(c[i][j],i,j,i,j))
return true;
}
}
return false;
}
int main(){
while(~scanf("%d%d",&n,&m)){
for(int i=0;i<n;i++)
scanf("%s",c[i]);
if(solve())
printf("Yes\n");
else
printf("No\n");
}
return 0;
}