戳这里还有其他数据结构的题目噢
https://blog.csdn.net/qq_45724947/article/details/115625130?spm=1001.2014.3001.5501
设计并验证以下算法:若矩阵采用三元组顺序表表示,设计并验证找出矩阵所有马鞍点的算法。
直接上代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX 500
#define M 100
#define N 100
typedef int arr_type;
//储存行 列 值
typedef struct {
int row;//从1 开始
int col;//从1 开始
arr_type value;
}array;
//储存三元组顺序表+总行数,总列数,总非零元素个数
typedef struct {
array arr[MAX];//从0开始
int rownum,colnum,all;
}sparse_matrix;
//生成随机稀疏矩阵三元组
arr_type rand_array(sparse_matrix *s1){
srand(time(NULL));
int r1;
r1 = s1->rownum * s1->colnum;
int k;
s1->all = 0;
//矩阵A随机生成
for(int i = 1;i <= s1->rownum;i++)
for(int j = 1;j <= s1->colnum;j++)
{
k = rand()%r1;
//printf("%d\n",k);
if(k < (r1/10))
{
s1->arr[s1->all].value = (rand()%9)+1;
s1->arr[s1->all].row = i;
s1->arr[s1->all].col = j;
s1->all++;
}
}
if(r1/s1->all > 20)
return 1;
return 0;
}
int minn[M] = {0},maxx[N] = {0};
void MinMax(sparse_matrix *s)///M行中最小,N列中最大
{
int i,j;
int ord = 0,turn = 1;
bool have = false;
for(i=1; i <= s->rownum; i++) ///求出每行最小数,存在minn[0...M-1]中
{
while(s->arr[ord].row == i)
{
if(turn == 1)
{
minn[i-1] = ord;
ord++;
turn = 0;
continue;
}
if(s->arr[minn[i-1]].value > s->arr[ord].value)
minn[i-1] = ord;
ord++;
}
turn = 1;
}
ord = 0;
for(j=1; j <= s->colnum; j++) ///求出每列最大数,存在maxx[0...N-1]中
{
//printf("%d",j);
while(1)// (1,2) (1,4) (2,3) (3,3) (3,5) (5,1) ord=012345,colnum=5,j>0,s->all=6,
{ // 0 1 2 3 4 5
while(s->arr[ord].col != j&&(ord < s->all))
{
if(ord == s->all-1)
break;
ord++;
}
if(turn == 1)
{
maxx[j-1] = ord;
turn = 0;
ord++;
continue;
}
else if(s->arr[maxx[j-1]].value < s->arr[ord].value)
maxx[j-1] = ord;
if(ord >= s->all-1)
{
turn = 1;
break;
}
}
}
for(i=1; i<s->rownum; i++)
for(j=1; j<s->colnum; j++)
if(minn[i-1] == maxx[j-1]&&( s->arr[minn[i-1]].row == s->arr[maxx[j-1]].row )&&
( s->arr[minn[i-1]].col == s->arr[maxx[j-1]].col ))///找到马鞍点
{
printf("array[%d][%d]=%d\n",s->arr[minn[i-1]].row,s->arr[minn[i-1]].col,s->arr[maxx[j-1]].value);
have=true;
}
if(!have)
printf("没有马鞍点\n");
}
void print_matrix(sparse_matrix a){
int ord=0,zero = 0;
for(int i = 1;i <= a.rownum;i++)
{
for(int j = 1;j <= a.colnum;j++)
{
if((i == a.arr[ord].row)&&
(j == a.arr[ord].col))
{
printf("% 3d",a.arr[ord].value);
ord++;
}
else
printf("% 3d",zero);
}
printf("\n");
}
printf("\n");
}
int main()
{
sparse_matrix a;
printf("请输入矩阵行和列数:\n");
scanf("%d %d",&a.rownum,&a.colnum);
if(rand_array(&a)){
printf("随机生成矩阵失败!\n");
return 0;
}
print_matrix(a);
MinMax(&a);
return 0;
}
(请不要直接复制使用。代码仅供参考,希望读者借此代码自身可以理解学习)
如果代码对您有帮助,不要忘记评论收藏噢~