题目链接:点击这里
题意:给出一个图,问能不能找到一个同样颜色的环路径。
直接从没搜过的点搜,如果在搜的过程中搜到一个不是从父亲节点转移过来的已经搜过的节点,那么就说明存在一个环。
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <vector>
#include <cstring>
#include <queue>
using namespace std;
#define maxn 55
#define move Move
const int move[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
char mp[maxn][maxn];
bool vis[maxn][maxn];
int n, m;
bool legal (int x, int y) {
return (x < n && x >= 0 && y < m && y >= 0);
}
bool dfs (int x, int y, int prex, int prey, char ch) {
vis[x][y] = 1;
for (int i = 0; i < 4; i++) {
int xx = x+move[i][0], yy = y+move[i][1];
if (!legal (xx, yy) || (xx == prex && yy == prey)) continue;
if (mp[xx][yy] == ch) {
if (vis[xx][yy] || dfs (xx, yy, x, y, ch)) return 1;
}
}
return 0;
}
int main () {
cin >> n >> m;
for (int i = 0; i < n; i++) cin >> mp[i];
memset (vis, 0, sizeof vis);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) if (!vis[i][j]) {
bool ok = dfs (i, j, -1, -1, mp[i][j]);
if (ok) {
cout << "Yes" << endl;
return 0;
}
}
}
cout << "No" << endl;
return 0;
}