将一个图读入邻接表 将邻接表读入一个图

数据结构与算法分析——c语言描述 练习3.14 答案


将邻接表读入一个图

#include"list.h"
#include<stdio.h>
#include<string.h>
#define MAXN 1000

int graph[MAXN][MAXN];
List spot[MAXN];
int n;

void graphToSpot() {
	for (int i = 0; i < n; i++) {
		spot[i] = CreatList();
		for (int j = 0; j < n; j++) {
			if (graph[i][j] == 1)
				Insert(j, spot[i]);
		}
	}
}

void printAll(List l) {
	Position p = Advance(l);
	while (p) {
		printf("%d ", Retrieve(p));
		p = Advance(p);
	}
}


int main() {
	memset(graph, 0, sizeof(graph));
	int temp;
	scanf("%d", &n);
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			scanf("%d", &temp);
			graph[i][j] = 1;
		}
	}
	graphToSpot();
	for (int i = 0; i < n; i++)
	{
		printAll(spot[i]);
		printf("\n");
	}
}

将一个图读入邻接表

#include"list.h"
#include<stdio.h>
#include<string.h>
#define MAXN 1000

int graph[MAXN][MAXN];
List spot[MAXN];
int n;

void spotTograph() {
	for (int i = 0; i < n; i++) {
		Position p = Advance(spot[i]);
		while (p) {
			graph[i][Retrieve(p)] = 1;
			p = Advance(p);
		}
	}
}




int main() {
	memset(graph, 0, sizeof(graph));
	int temp;
	scanf("%d", &n);
	
	for (int i = 0; i < n; i++) {
		spot[i] = CreatList();
		while (scanf("%d", &temp) == 1) {
			Insert(temp, spot[i]);
		}
		getchar();
	}


	spotTograph();
	
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < n; j++) {
			printf("%d ", graph[i][j]);
		}
		printf("\n");
	}
}


你可能感兴趣的:(将一个图读入邻接表 将邻接表读入一个图)