这个是我自己写的,下面那个是看的别人的,其实大致都是一样的,通过四次循环,挨个求和比较,都很麻烦,但重点在于,对于已知变量的运用,当我需要在最内层循环用变量确定a数组组元时,是通过引入新的变量来搞定的,而这个人则是通过对已有变量的处理来表示,这个地方感觉还是蛮差距的。
int main()
{int m = 0, n = 0;int r = 0, s = 0;int a[100][100] = { 0 };int b[100][100] = { 0 };int i = 0, j = 0;scanf("%d %d", &m, &n);for (i = 0; i < m; i++){for (j = 0; j < n; j++){scanf("%d", &a[i][j]);}}scanf("%d %d", &r, &s);for (i = 0; i < r; i++){for (j = 0; j < s; j++){scanf("%d", &b[i][j]);}}//int sum = 0;int min = 100000;int r2 = 0, c2 = 0;int ia1 = 0, ja1 = 0;for(int ia=0;ia<m-r+1;ia++){for (int ja = 0; ja < n-s+1; ja++){ia1 = ia; sum = 0;for (int ib = 0; ib < r; ib++){ja1 = ja;for (int jb = 0; jb < s; jb++){if ((a[ia1][ja1] - b[ib][jb]) < 0)sum += -(a[ia1][ja1] - b[ib][jb]);elsesum += a[ia1][ja1] - b[ib][jb];ja1++;}ia1++;}if (min > sum){min = sum; r2 = ia; c2 = ja;}}}for ( i = r2; i < r+r2; i++){for (j = c2; j < s+c2; j++){printf("%d ",a[i][j]);}printf("\n");}return 0;
}
参考代码:#include<stdio.h>#include<stdlib.h>#define MAX_INT ~((unsigned int)0)>>1;//输出int型可以表示的最大值int main(){/*输入函数,注意是二维数组,也就是行列*/int m,n,i,j,r,s;int a[101][101],b[101][101];scanf("%d %d\n",&m,&n);for(i=0;i<m;i++){for(j=0;j<n;j++){scanf("%d ",&a[i][j]);}scanf("\n");}scanf("%d %d\n",&r,&s);for(i=0;i<r;i++){for(j=0;j<s;j++){scanf("%d ",&b[i][j]);}scanf("\n");}int drow,dcol,min;min =MAX_INT;for(i=0;i<m-r+1;i++)//注意行列和矩形{for(j=0;j<n-s+1;j++)//上面两个for选定了一个值(左上角元素),然后从该值出发进行选择矩形{int k,l,sum=0;for(k=0;k<r;k++)//执行要选择出来的矩形{for(l=0;l<s;l++)sum=sum+abs(abs(a[i+k][j+l]-b[k][l]));}if(sum<min)//要取最小的,行列{drow=i;dcol=j;min=sum;//drow和dcol是在大矩形当中的起始值}}}for (i = 0; i < r; i++) {for (j = 0; j < s; j++)printf("%d ", a[drow + i][dcol + j]);printf("\n");}return 0;}