• 图的算法


    1.编一C程序,它能根据读入的数据构造有向图G,并输出G的DFS遍历序列(从V0开始),
    图的输入形式为n V0 Vi0 V1 Vi1 V2 Vi2...Vi Vin -1 -1(-1,-1为输入结束标记,其余的值都>=0且
    它们都是整数,且100>n>0。(注:程序的可执行文件名必须是 e2.exe,存于你的账号或其debug目录下。)
    输入: 9 0 1 0 2 0 7 1 2 1 4 2 3 3 5 3 6 4 3 4 5 7 8 8 6 -1 -1

    #include<stdio.h>
    #define MAX 100
    typedef enum{False,True} Boolean;
    int G[MAX][MAX];
    int n;
    //建立图的邻接矩阵G[][]
    void GreateG(){
    	int i,j;
    	printf("Input the number of the node:");
    	scanf("%d", &n);
    	printf("
    ");
    	for(i=0;i<n;i++){
    		for(j=0;j<n;j++){
    			G[i][j]=0;
    		}
    	}	
    	do{
    		scanf("%d%d", &i,&j);
    		G[i][j]=1;
    	}while((i!=-1) && (j!=-1));
    }
    
    
    //拓扑排序,输出拓扑序列
    void TopSort(){
    
    	int i,j;
    	//按照无前驱顶点优先思想,degree[]存放个节点的入度
    	int degree[100];
    	Boolean visited[MAX],flag=True;
    	printf("The Topolgical Order as follow:");
    	for(i=0;i<n;i++){
    		degree[i]=0;
    		visited[i]=False;
    	}
    	printf("
    ");
    	while(flag==True){
    		for(i=0;i<n;i++){
    			for(j=0;j<n;j++){
    				degree[i]=G[j][i]+degree[i];
    			}
    		}
    		i=0;
    		//最先输出入度为0的顶点
    		while((i<n) && (degree[i]!=0) || visited[i]==True){
    			i++;
    		}
    		//所有节点均已输出结束,否则说明存在环,无拓扑序列
    		if(i<n){
    			printf("%d",i);
    			visited[i]=True;
    			for(j=0;j<n;j++){
    				G[i][j]=0;
    				degree[j]=0;
    			
    			}
    		}else{
    			flag = False;
    		}
    		
    	}
    }
    
    void main(){
    	GreateG();
    	TopSort();
    	printf("
    ");
    }
    
  • 相关阅读:
    268. Missing Number
    217. Contains Duplicate
    189. Rotate Array
    Two Sum II
    122. Best Time to Buy and Sell Stock II
    169. Majority Element
    C# ConfigurationManager不存在问题解决
    C# sqlhelper
    C#基础
    数据库事务日志已满的解决办法
  • 原文地址:https://www.cnblogs.com/snail-gao/p/11774792.html
Copyright © 2020-2023  润新知