codeforces 510B (dfs 水)

题目链接:点击这里

题意:给出一个图,问能不能找到一个同样颜色的环路径。

直接从没搜过的点搜,如果在搜的过程中搜到一个不是从父亲节点转移过来的已经搜过的节点,那么就说明存在一个环。

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值