问题是:检查两个矩阵,如果一个是另一个矩阵的子矩阵。
我在这里遇到的问题是for
循环,在代码中注释为“// problem”。当程序第一次运行时,提到的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
答案 0 :(得分:4)
在开始查找子矩阵之前,您需要将check
重置为零。
一旦你找到它就打破(或者用旗子来表明它是否被发现)。
从你的输出中,(假设你试图找到2x2矩阵)它连续发现它Checked
打印的次数,但它的值也是第一次打印的5,这使得你的程序可以打印{ {1}}。
像:
"It does not exist"