题目
小鑫的女朋友被魔王抢走了!
魔王留给小鑫一张n*m大的表,上面有各种各样的颜色,用A-Z这26个字母来表示。魔王留给他一个任务,如果小鑫可以在这张表中找出任意一个长度大于1的环,并且这个环的颜色是相同的,魔王就把小鑫的女朋友还给他。为了从魔王手中夺回他的女朋友,小鑫请你帮忙,你能帮帮他吗?
Input
多组输入。
每组的第一行有两个整数n,m。代表表的大小。
接下来是由A-Z的一些字母所构成的n行m列的表。
1<=n,m<=200
Output
如果可以救回他的女朋友,输出Yes,否则输出No
Example Input
4 7
ABCBBAA
BCBCBCB
AABBCCA
ACCCBBB10 3
AAC
ABB
BBA
AAC
CBC
CCA
CBB
CCA
CCB
BAA
Example Output
false
true
#include <iostream>
using namespace std;
char a[100][100];
int book[100][100];
int x[4] = { 0,0,1,-1 };
int y[4] = { 1,-1,0,0 };
int n, m;
bool state;
void dfs(int i, int j,int father_x,int father_y) {
//i,j是当前点的横纵坐标
//father_x,father_y是上一个点的横纵坐标
book[i][j] = 1;
for (int t = 0; t < 4; t++) {
//遍历(i,j)周边四个点
int temp_i = i + x[t];
int temp_j = j + y[t];
if ((temp_i >= 0) && (temp_i < n) && (temp_j >= 0) && (temp_j < m) && (a[temp_i][temp_j] == a[i][j])) {
//这个新的点在范围内且和当前点字母相同
if (!book[temp_i][temp_j])
//继续探索
dfs(temp_i, temp_j, i, j);
else if (temp_i != father_x&&temp_j != father_y) {
//当这个新的点之前已经被访问过,但不是当前该点的上一个点(父节点)
state = true;
return;
}
}
}
}
int main() {
while (cin >> n >> m) {
for(int i=0;i<n;i++)
for (int j = 0; j < m; j++) {
cin >> a[i][j];
}
state = false;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (!book[i][j]) {//已经遍历过的点不需要再开始,因为在之前点dfs时经过了该点,要有环早有了
dfs(i, j, i, j);
if (state)
break;
}
}
if (state)
break;
}
if (state)
cout << "true" << endl;
else
cout << "false" << endl;
}
}
void dfs(int i, int j,int father_x,int father_y) {
book[i][j] = 1;
for (int t = 0; t < 4; t++) {
int temp_i = i + x[t];
int temp_j = j + y[t];
if ((temp_i >= n) || (temp_i < 0) || (temp_j >= m) || (temp_j < 0)||(a[i][j]!=a[temp_i][temp_j]))
continue;
if (!book[temp_i][temp_j])
dfs(temp_i, temp_j, i, j);
else if (temp_i != father_x&&temp_j != father_y) {
state = true;
return;
}
}
}