0

问题是:检查两个矩阵,如果一个是另一个的子矩阵。

我在这里面临的问题是for代码中注释为“//问题”的循环。当程序第一次运行时,提到的for循环不能正常工作。

#include <stdio.h>
#define N 10

int
main ()
{

  char matrix1[N][N], matrix2[N][N];
  int i, j, row1, col1, row2, col2, k, l, m, n, check = 0;

  //First Matrix
  printf ("Enter the data\n");
  printf ("Enter the size of rows\n");
  scanf ("%d", &row1);   
  printf ("Enter the size of columns\n");
  scanf ("%d", &col1);   
  printf ("Now enter the values please\n");

  //Putting Values In First Matrix
  for (i = 0; i < row1; i++)
    {
      for (j = 0; j < col1; j++)
        {
          printf ("Please enter the %dth row and %dth column\n", i + 1,
                  j + 1);
          scanf ("%s", &matrix1[i][j]);
        }
    }

  //Second Matrix
  printf ("Enter the data\n");
  printf ("Enter the size of rows\n");
  scanf ("%d", &row2);   
  printf ("Enter the size of columns\n");
  scanf ("%d", &col2);   
  printf ("Now enter the values please\n");

  //Putting Values In Second Matrix
  for (i = 0; i < row2; i++)
    {
      for (j = 0; j < col2; j++)
        {
          printf ("Please enter the %dth row and %dth column\n", i + 1,
                  j + 1);
          scanf ("%s", &matrix2[i][j]);
        }
    }

  //Checking Both Matrices
  for (i = 0; i < row1; i++)
    {
      for (j = 0; j < col1; j++)
        {
          if (matrix1[i][j] == matrix2[0][0])
            {
              k = i;
              l = j;
              for (m = 0; m < row2; m++)
                {
                  for (n = 0; n < col2; n++)
                    {           //problem
                      if (matrix1[k][l] == matrix2[m][n])
                        {
                          check++;
                          printf ("Checked\n");
                        }
                      l++;
                    }
                  l = j; 
                  k++;   
                }
            }
        }
      printf ("hello\n");
    }
  if (check == row2 * col2)
    {
      printf ("It exists\n");
    }
  else
    {
      printf ("It doesn't exist\n");
    }
}

这是输出:

 Checked
 hello
 Checked
 Checked
 Checked
 Checked
 hello
 hello
 It doesn't exist
4

1 回答 1

4

check在开始查找子矩阵之前,您需要重置为零。一旦你找到它也要打破(或者有标志来表明它是否被发现)。

从你的输出来看,(假设你试图找到 2x2 矩阵)它发现它Checked连续打印了几次,但它的值也将是 5 计算第一次打印,这使你的程序打印"It does not exist"

喜欢:

int is_found = 0;
... //some code
//Checking Both Matrices
for (i = 0; i < row1; i++)
{
  for (j = 0; j < col1; j++)
    {
      check = 0;   //reset check
      if (matrix1[i][j] == matrix2[0][0])
        {
      ... //your code to check matrix.
      ...
      }//if end
      if(check == row2*col2) 
      {
          is_found = 1;
      }
      ...
   } //for j end
   if(is_found)
      break;
   ...

 ...
 if(is_found)
    printf("It exists\n");
于 2012-08-16T08:03:47.917 回答