我想打印数组的[i] [j]个元素,并保留[j] [i]个元素。
void printWeightList() {
//How many links there are: numOfEdges
int ARRAY[MAX][MAX];
for (int i = 0; i < MAX; i++) {
for (int j = 0; j < MAX; j++) {
ARRAY[i][j] = weightList[i][j];
}
}
int i = 0, j = 0;
for (i = 0; i < vertexCount; i++) {
for (j = 0; j < vertexCount; j++) {
if (ARRAY[i][j] != 0) {
printf("%c -> %c: ", lstVertices[i] ->label, lstVertices[j] ->label);
printf("%d\n", ARRAY[i][j]);
ARRAY[j][i] = 0; //TO REMOVE [j][i] ELEMENTS
}
}
}
printf("\n");
}
以上是我想到的一种解决方案。我不想更改weightList [] [],因为它是全局定义的,所以我创建了另一个数组。这增加了空间复杂度。我想要一个不太复杂的解决方案。
答案 0 :(得分:0)
您需要检查主对角线的条件是j等于i时。
#include <stdio.h>
#include <stdlib.h>
void printWeightList(void);
#define MAX 6
int weightList[MAX][MAX] = { 1, 2, 4 , 5 , 6, 7,
8, 9, 10, 11, 12, 13,
14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31,
32, 33, 34, 34, 35, 36,
};
int main (int argc, char *argv[])
{
printWeightList();
return(0);
}
void printWeightList(void) {
int ARRAY[MAX][MAX];
int i = 0;
int j = 0;
for ( i = 0; i < MAX; i++) {
for (int j = 0; j < MAX; j++) {
/*If we are on the main diagonal clear its elements*/
if (i == j) {
ARRAY[i][j] = 0;
}
else
{
ARRAY[i][j] = weightList[i][j];
}
}
}
for ( i = 0; i < MAX; i++) {
for ( j = 0; j < MAX; j++) {
printf("%d\t", ARRAY[i][j]);
}
printf("\n");
}
return;
}