深度优先搜索——神奇的矩环


题目
小鑫的女朋友被魔王抢走了!
魔王留给小鑫一张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
ACCCBBB

10 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;
            }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值