C:检查矩阵是否是另一个矩阵的子矩阵的函数

时间:2017-11-15 19:46:14

标签: c matrix

给定两个矩阵我想检查一个是否包含在另一个矩阵中,我有矩阵的维数,我写了一个不起作用的函数,我不知道为什么:这里是代码解释:

               /*Where m,n are the dimensions of the first matrix 
                and u,v the dimensions of the second one, the integer
                 pointers are to remember from where,row and column,
                 (for the first time) the matrices overlap */        


            int function(int a[][SIZE],int m,int n, int  b[][SIZE],int u,int v, int *r,int *c)
                    {
                     int i,j,x,y,cont=0;

        /*The first two 'for' cycles are to choose a suitable starting point for the confrontation  */ 
                     for(i=0;i<m-u+1;i++)        
                     {
                         for(j=0;j<n-v+1;j++)
                         {
                             cont=0; /*Every time it choose the starting point, the counter start from 0 */
                                 for(x=0;x<u;x++)
                                 {
                                     for(y=0;y<v;y++)
                                     {
                                         if(a[i+x][j+y] == b[x][y]) /*Here there is the confrontation between the elements*/
                                         {
                                             cont++; /*This counts the number of equal elements between the second matrix b and the (same-dimension-part of) first matrix*/


                                         }

                                     } 
                                 }      /*It does the confrontations as many times as the elements of b, so u*v times */

                                if(cont==u * v) /*If the elements are equal for every element of b, the program return 1*/
                                 {
                                     *r=i;
                                     *c=j;
                                     return 1;


                                 }

                         }
                     }

                   /*If it has never returned one, it return 0*/
                     return 0;
                    }

这里有一个使用函数的例子:

int function(int a[][SIZE],int m,int n, int  b[][SIZE],int u,int v, int *r,int *c);

        int main()
        {
         int i,j,x=0,y=0;
         int a[10][10],b[2][2];
         int *r=&x,*c=&y;

        srand(time(NULL));

        for(i=0;i<10;i++)
         {
         for(j=0;j<10;j++)
        {
             if(i<2 && j<2)
                 b[i][j]=rand()%2;

         a[i][j]=rand()%2;
        }
        }
        i=function(a,10,10,b,2,2,r,c);
        if(i==1)
             printf("(%d , %d)\n", *r,*c);
        else
             printf("b is not a submatrix of a\n");

        return 0;
        } 

P.S。我尝试每次a[i+x][j+y]==b[x][y]打印元素a[i+x][j+y]b[x][y]。但是碰巧b [x] [y]有时是错误的值(例如,如果b仅由1组成,则碰巧在对抗b [x] [y]打印为零之后)。

0 个答案:

没有答案