Codeforces Round #290 (Div. 2) B. Fox And Two Dots(搜索,DFS)

题目链接:https://codeforces.com/contest/510/problem/B

题意:

找出矩阵中由一种字母组成的环(至少由四个点组成)。

思路:

给每个点设置一个搜索深度,如果同种字母的两个相邻点深度相差大于等于3,那么它们就可以组成一个环。

#include <bits/stdc++.h>
using namespace std;

const int M=60;

char MP[M][M];
int dep[M][M];
bool flag;

int dir[4][2]={{-1,0},{1,0},{0,-1},{0,1}};

void dfs(int a,int b,char color,int depth)
{
    dep[a][b]=depth;

    for(int i=0;i<4;i++)
    {
        int x=a+dir[i][0];
        int y=b+dir[i][1];
        
        if(MP[x][y]==color)
        {
            if(dep[x][y]==0)
                dfs(x,y,color,depth+1);
            else if(depth-dep[x][y]>=3)
                flag=true;
        }
    }

}

int main()
{
    int n,m;cin>>n>>m;

    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++)
            cin>>MP[i][j];

    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++)
            if(dep[i][j]==0)
                dfs(i,j,MP[i][j],1);

    cout<<(flag?"Yes":"No");

    return 0;
}

 

posted @ 2020-04-02 23:35  Kanoon  阅读(123)  评论(0)    收藏  举报