寻觅数组相邻相同的数值

寻找数组相邻相同的数值

给定数组a[M][N]以及指定位置m,n,
要求找出与a[m][n]相邻(所谓相邻就是上下左右)且相等的数值,
若找到再以该相邻数值为基准继续寻找与其相邻且相等的数值。
最后求出个数。
如下:指定的数值是a[3][2],那么与a[3][2]相等且相邻的数值就是6个了
要求实现函数find

C/C++ code


#include "stdio.h"
#define M 5
#define N 4

int find(int a[M][N],int m,int n);

int main()
{
    int a[M][N]={
            {1,1,1,3},
            {1,2,3,4},
            {2,1,3,3},
            {1,3,3,3},
            {1,2,3,2}
        };
    int count=find(a,3,2);
    printf("%d\n",count);
    return 0;
}





------解决方案--------------------
C/C++ code

#include "stdio.h"
#define M 5
#define N 4

int myfind(int a[M][N],int b[M][N],int m,int n)
{
    int res=1;
    if (m>0)
    {
        if (b[m-1][n]==0 && a[m-1][n]==a[m][n]) 
        {//up
            b[m-1][n]=1;
            res+=myfind(a,b,m-1,n);
        }
    }
    if (m<M-1)
    {
        if (b[m+1][n]==0 && a[m+1][n]==a[m][n]) 
        {//down
            b[m+1][n]=1;
            res+=myfind(a,b,m+1,n);
        }
    }
    if (n>0)
    {
        if (b[m][n-1]==0 && a[m][n-1]==a[m][n]) 
        {//left
            b[m][n-1]=1;
            res+=myfind(a,b,m,n-1);
        }
    }
    if (n<N-1)
    {
        if (b[m][n+1]==0 && a[m][n+1]==a[m][n]) 
        {//right
            b[m][n+1]=1;
            res+=myfind(a,b,m,n+1);
        }
    }
    return res;

}

int find(int a[M][N],int m,int n)
{
    int b[M][N];
    for (int i=0;i<M;i++)
    {
        for (int j=0;j<N;j++)
        {
            b[i][j]=0;
        }
    }
    b[m][n]=1;
    return myfind(a,b,m,n);
}

int main()
{
    int a[M][N]={
            {1,1,1,3},
            {1,2,3,4},
            {2,1,3,3},
            {1,3,3,3},
            {1,2,3,2}
        };
    int count=find(a,3,2);
    printf("%d\n",count);
    return 0;
}

------解决方案--------------------
C/C++ code
可以用递归,类似图形填充的种子填充方法

void fill(int x, int y)
{
    int t = getpixel(x, y);
    if(t != RED && t != GREEN)
    {
        putpixel(x, y, GREEN);
    
        fill(x + 1, y);
        fill(x - 1, y);
        fill(x, y + 1);
        fill(x, y - 1);
    }
}