B. Fox And Two Dots
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
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 d1, d2, ..., dka cycle if and only if it meets the following condition:
Determine if there exists a cycle on the field.
Input
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
Output "Yes" if there exists a cycle, and "No" otherwise.
Examples
input
Copy
3 4 AAAA ABCA AAAA
output
Copy
Yes
input
Copy
3 4 AAAA ABCA AADA
output
Copy
No
input
Copy
4 4 YYYR BYBY BBBY BBBY
output
Copy
Yes
input
Copy
7 6 AAAAAB ABBBAB ABAAAB ABABBB ABAAAB ABBBAB AAAAAB
output
Copy
Yes
input
Copy
2 13 ABCDEFGHIJKLM NOPQRSTUVWXYZ
output
Copy
No
Note
In first sample test all 'A' form a cycle.
In second sample there is no such cycle.
The third sample is displayed on the picture above ('Y' = Yellow, 'B' = Blue, 'R' = Red).
题意:找出图中是否有相同字母组成的环
代码:
#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define INF 0x3f3f3f3f
#define mem(a, x) memset(a, x, sizeof(a))
#define X first
#define Y second
#define rep(i,a,n) for (int i=a;i=a;i--)
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define SZ(x) ((int)(x).size())
using namespace std;
typedef vector vi;
typedef long long ll;
typedef pair pii;
const double PI = acos(-1.0);
const ll mod = 1000000007;
ll powmod(ll a, ll b) { ll res = 1; a %= mod; assert(b >= 0); for (; b; b >>= 1) { if (b & 1)res = res * a%mod; a = a * a%mod; }return res; }
ll gcd(ll a, ll b) { return b ? gcd(b, a%b) : a; }
//------------------------------------head------------------------------------
const int N = 55;
bool vis[N][N], f = 0;
char g[N][N];
int dir[4][2] = { 1, 0, -1, 0, 0, 1, 0, -1 }, tx, ty, n, m, sx, sy;
// xia shang you zuo
bool ing(int x, int y) {
return x >= 0 && x < n && y >= 0 && y < m;
}
void dfs(int x, int y, int step) {
if (f) return;
vis[x][y] = 1;
rep(i, 0, 4) {
tx = x + dir[i][0];
ty = y + dir[i][1];
if (ing(tx, ty) && g[tx][ty] == g[sx][sy]) {
if (tx == sx && ty == sy && vis[tx][ty] && step > 2) {
f = 1;
return;
} else if (!vis[tx][ty]) {
dfs(tx, ty, step + 1);
}
}
}
}
int main() {
cin >> n >> m;
rep (i, 0, n) cin >> g[i];
rep(i, 0, n) {
rep (j, 0, m) {
mem(vis, false);
sx = i, sy = j;
dfs(i, j, 1);
if (f) goto out;
}
}
out:
puts(f ? "Yes" : "No");
}