一、二维数组练习
1.找出一个二维数组中的鞍点, 即:该位置上的元素在该行上最大、在该列上最小。也可能没有鞍点。
解法一:
#include <stdio.h>
int main(void)
{
int a[3][3] = {1,2,9,4,5,10,8,9,8};
int i = 0;
int j = 0;
int k = 0;
int l = 0;
int m = 0;
int flag = 0;
for (i = 0; i < 3; ++i)
{
for (j = 0; j < 3; ++j)
{
printf("%d ",a[i][j]);
}
putchar('\n');
}
for (i = 0; i < 3; ++i)
{
int max = a[i][0];
for (j = 1; j < 3; ++j)
{
if (a[i][j] > max)
{
max = a[i][j];
k = j;
}
}
int min = a[0][k];
l = 0; //l 每次 从 0 开始 和 m 同步
for (m = 1; m < 3; m++)
{
if (a[m][k] < min)
{
min = a[m][k];
l = m;
}
}
if (l == i)
{
flag = 1;
printf("found = (%d,%d) = %d\n",i,k,a[i][k]);
}
}
if (flag == 0)
{
printf("not found!\n");
}
return 0;
}
解法二:
#include <stdio.h>
int main(void)
{
//int a[3][3] = {1,2,9,4,5,10,8,9,8};
int a[3][3] = {1,2,3,4,5,7,8,9,10};
int i = 0;
int j = 0;
int k = 0;
int l = 0;
int m = 0;
int flag = 0;
for (i = 0; i < 3; ++i)
{
for (j = 0; j < 3; ++j)
{
printf("%d ",a[i][j]);
}
putchar('\n');
}
for (i = 0; i < 3; ++i)
{
int max = a[i][0];
for (j = 1; j < 3; ++j)
{
if (a[i][j] > max)
{
max = a[i][j];
k = j;
}
}
for (m = 0; m < 3; m++)
{
if (a[m][k] < max)
{
break;
}
}
if (m == 3)
{
flag = 1;
printf("found = (%d,%d) = %d\n",i,k,a[i][k]);
}
}
if (flag == 0)
{
printf("not found!\n");
}
return 0;
}
解法三:
#include<stdio.h>
int main(void)
{
int a[3][3];// = {1,2,3,4,5,6,7,8,9};
printf("请输入一个3*3的二维数组:\n");
int i,j;
i = 0;
j = 0;
for(i = 0;i < 3;++i)
{
for(j = 0;j < 3;++j)
{
scanf("%d",&a[i][j]);
}
}
int m,n,p,q,t;
t = 0;
for(i = 0;i < 3;++i)
{
for(j = 0;j < 3;++j)
{
q =0;
for(m = 0;m < 3;++m)
{
if(m == j)
++m;
if(m >= 3)
break;
if(a[i][j] > a[i][m])
++q;
if(q == 2)
{
p = 0;
for(n = 0;n < 3;++n)
{
if(n == i)
++n;
if(n >= 3)
break;
if(a[i][j] < a[n][j])
++p;
if(p == 2)
{
t = 1;
printf("a[%d][%d] = %d\n",i,j,a[i][j]);
}
}
}
}
}
}
if(t != 1)
printf("没有鞍点\n");
return 0;
}
二、数独
第一个数始终在第一行中间,下一个数向右在向上上移动,如果已经有了则数,则在原数下面赋值
#include <stdio.h>
#include <strings.h>
int main(void)
{
int n;
printf("Input a num:");
scanf("%d",&n);
int a[n][n];
//printf("sizeof(a) = %ld\n",sizeof(a));
bzero(a,sizeof(a));
int i = 0;
int j = 0;
int k = 1;
int x,y;
a[0][n/2] = 1;
i = 0;
j = n/2;
for (k = 2; k <= n*n; ++k)
{
x = i;
y = j;
++j;
if (j > n-1)
{
j = 0;
}
--i;
if (i < 0)
{
i = n-1;
}
if (a[i][j] != 0)
{
i = x;
j = y;
++i;
if (i > n-1)
{
i = 0;
}
}
a[i][j] = k;
}
for (i = 0; i < n; ++i)
{
for (j = 0; j < n; ++j)
{
printf("%d ",a[i][j]);
}
putchar('\n');
}
return 0;
}