dfs练习题

/*
Fox Ciel is playing a mobile puzzle game called "Two Dots". The basic levels are played on a board of size n?×?m cells, like this:


Each cell contains a dot that has some color. We will use different uppercase Latin characters to express different colors.

The key of this game is to find a cycle that contain dots of same color. Consider 4 blue dots on the picture forming a circle as an example. Formally, we call a sequence of dots d1,?d2,?...,?dk a cycle if and only if it meets the following condition:

These k dots are different: if i?≠?j then di is different from dj.
k is at least 4.
All dots belong to the same color.
For all 1?≤?i?≤?k?-?1: di and di?+?1 are adjacent. Also, dk and d1 should also be adjacent. Cells x and y are called adjacent if they share an edge.
Determine if there exists a cycle on the field.

Input
The first line contains two integers n and m (2?≤?n,?m?≤?50): the number of rows and columns of the board.

Then n lines follow, each line contains a string consisting of m characters, expressing colors of dots in each line. Each character is an uppercase Latin letter.

Output
Output "Yes" if there exists a cycle, and "No" otherwise.

Examples
Input
3 4
AAAA
ABCA
AAAA
Output
Yes
Input
3 4
AAAA
ABCA
AADA
Output
No
Input
4 4
YYYR
BYBY
BBBY
BBBY
Output
Yes
Input
7 6
AAAAAB
ABBBAB
ABAAAB
ABABBB
ABAAAB
ABBBAB
AAAAAB
Output
Yes
Input
2 13
ABCDEFGHIJKLM
NOPQRSTUVWXYZ
Output
No
Note
In first sample test all 'A' form a cycle.

In second sample there is no such cycle.

The third sample is displayed on the picture above ('Y' = Yellow, 'B' = Blue, 'R' = Red).
*/ 

/*
这题  利用  dfs + 回溯 来做的;

为了 避免重复  我在 dfs中 记录啦  3 个点
这样 找到 可循环时  可直接 return 1; 
*/

#include<stdio.h>
#include<string.h>
int n,m,h,l,t;
char ss[60][60];
int vis[60][60];
int b[4][2] = {1,0,0,1,0,-1,-1,0};
int dfs(int x,int y,int xl,int yl)
{
    int x1=0,y1=0,r;
    vis[x][y]=1;
    for(int i=0;i<4;i++)
    {
        x1 = x+b[i][0];
        y1 = y+b[i][1];
        if((x1!=xl||y1!=yl)&&ss[x1][y1]==ss[x][y]&&vis[x1][y1]==1)    return 1;
        if(x1>=0&&y1>=0&&x1<n&&y1<m&&vis[x1][y1]==0&&ss[x1][y1]==ss[x][y])
        {
            r =dfs(x1,y1,x,y);
            if(r==1)    return 1;
        }
    }
    return 0;
}
int main()
{
    scanf("%d%d",&n,&m);
    for(int i=0;i<n;i++)    scanf("%s",ss[i]);
    h=0;
    memset(vis,0,sizeof(vis));
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        if(vis[i][j]==0)
        {
            h = dfs(i,j,0,0);
            if(h==1)    break;
        }
        if(h==1)    break;
    }
    if(h)    printf("Yes");
    else     printf("No");
}

猜你喜欢

转载自blog.csdn.net/lijianzhong1/article/details/81347572