题目描述
Fox Ciel is playing a mobile puzzle game called “Two Dots”. The basic levels are played on a board of size n × m cells, like this:
Each cell contains a dot that has some color. We will use different uppercase Latin characters to express different colors.
The key of this game is to find a cycle that contain dots of same color. Consider 4 blue dots on the picture forming a circle as an example.
Formally, we call a sequence of dots $d_1$, $d_2$, …, $d_k$ a cycle if and only if it meets the following condition:
- These k dots are different: if i ≠ j then $d_i$ is different from $d_j$.
- k is at least 4.
- All dots belong to the same color.
- For all $1 ≤ i ≤ k - 1$: $d_i$ and $d_i$ + 1 are adjacent. Also, dk and d1 should also be adjacent. Cells x and y are called adjacent if they share an edge.
Determine if there exists a cycle on the field.
输入描述
The first line contains two integers n and m $(2 ≤ n, m ≤ 50)$: the number of rows and columns of the board.
Then n lines follow, each line contains a string consisting of m characters, expressing colors of dots in each line. Each character is an uppercase Latin letter.
输出描述
Output “Yes” if there exists a cycle, and “No” otherwise.
题意分析
在一个n*m的矩阵中,能否用同一种字母组成一个环,从起点点开始上下左右,并且将途经所有点标记,如果最后能回到起点,说明能组成一个环,要注意一点的就是,搜索过程中下一个点不能与上一个点相同
样例输入
3 4
AAAA
ABCA
AAAA
样例输出
Yes
AC代码
#include<bits/stdc++.h>
#pragma GCC optimize(2)
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef map<int, int> mii;
typedef map<ll, ll> mll;
#define ull unsigned long long
#define IOS ios_base::sync_with_stdio(0); cin.tie(0);cout.tie(0);
const int maxn=1e6+10;
const ll mod=1e9+7;
const int INF = 0x3f3f3f3f;
int n,m;
char a[55][55];
int vis[55][55];
int d1[4]= {1,-1,0,0},d2[4]= {0,0,1,-1};
int f=0;
bool judge(int x,int y) {
if(x<0||y<0||x>=n||y>=m)return false;
else return true;
}
void dfs(int x,int y,int xx,int yy) {
if(vis[x][y]) {
f=1;
return;
}
vis[x][y]=1;
for(int i=0; i<4; i++) {
int nx,ny;
nx=x+d1[i];
ny=y+d2[i];
if(judge(nx,ny) && a[nx][ny]==a[x][y] && (nx!=xx||ny!=yy) ) {
dfs(nx,ny,x,y);
}
}
}
int main() {
IOS;
int i,j;
cin>>n>>m;
for(i=0; i<n; i++) {
for(j=0; j<m; j++) {
cin>>a[i][j];
}
}
for(i=0; i<n; i++) {
for(j=0; j<m; j++) {
if(!vis[i][j]) {
dfs(i,j,i,j);
if(f)break;
}
}
}
if(f)cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}