圖的存儲方式(鄰接矩陣)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
	int nu;
	int v1 = -1,v2 = -1;
	puts("input the number of vertex:");
	while( 1 != scanf("%d",&nu))
		getchar();
	const int N = nu;
	printf("the number of vertex is : %d\n",N);
	int (*matrix)[N] = (int(*)[N])malloc(sizeof(int) * N * N);
	memset(matrix,0,N*N);
	puts("input the relation of yout graph,like [1,2]:");
	while (1)
	{
		while( 2 != scanf("%d,%d",&v1,&v2))
			getchar();
		if(v1 == v2)
			break;
		if(v1 < 0 || v1 >= N || v2 < 0 || v2 >= N)
			continue;
		matrix[v1][v2] = matrix[v2][v1] = 1;
	}

	for(v1 = 0; v1 < N; v1 ++)
	{
		printf("V%d:  ",v1);
		for(v2 = 0; v2 < N; v2 ++)
			if(matrix[v1][v2])
				printf(" V%d,",v2);
		putchar(8);
		putchar(32);
		putchar(10);//消除最後打印時的逗號
	}
	free(matrix);
	return 0;
}
相關文章
相關標籤/搜索