Graph

2019-03-31  本文已影响0人  綿綿_

Adjacency Matrix

static final int MaxNum=20; //max num of vertexes
    
    {
        static final int MaxValue=67789;
        class GraphMatrix
        char[] Vertex = new char[MaxNum]; //sava info. of vertex
        int GType; //Type of vertex(directed or undirected)
        int VertexNum;
        int EdgeNum;
        int [][] EdgeWeight = new int[MaxNum][MaxNum]; //save edge weight
        int [] isTrav = new int [MaxNum]; //sign of traveled
    }

Create a graph

public class Graph {
    static Scanner input = new Scanner(System.in);
    
    static void CreateGraph(GraphMatrix GM)
    {
        int i,j,k;
        int weight;
        char EstartV,EendV; //  start and end vertex of of edge;
        
        System.out.println("enter the info. of graph");
        for(i=0;i<GM.VertexNum;i++)  //enter the vertex
        {
            System.out.printf("the %d vertex", i+1);
            GM.Vertex[i]=(input.next().toCharArray())[0]; //save in array
        }
        System.out.println("enter the edge and the weight");
        for(k=0;k<GM.EdgeNum;k++)
        {
            System.out.printf("the %d edge", k+1);
            EstartV=input.next().charAt(0);
            EendV=input.next().charAt(0);   
            weight=input.nextInt();
            for(i=0;EstartV!=GM.Vertex[i];i++); //search start vertex in 
                                                //those vertexes that we already have
            for(j=0;EendV!=GM.Vertex[j];j++);   //search end vertex in ...
            GM.EdgeWeight[i][j]=weight;    //save weight in corresponding position
            if(GM.GType==0) //if graph is undirected 
            {
                GM.EdgeWeight[j][i]=weight; //save data diagonally
            }
        }
    }
    
}

Clear a graph

void ClearGraph(GraphMatrix GM)
    {
        int i,j;
        for(i=0;i<GM.VertexNum;i++)
        {
            for(j=0;j<GM.VertexNum;j++)
            {
                GM.EdgeWeight[i][j]=GM.MaxValue;
            }
        }
    }

Print a Graph

void DisplayGraph(GraphMatrix GM)
    {
        int i,j;
        for(j=0;j<GM.VertexNum;j++)
        {
            System.out.printf("\t%c",GM.Vertex[j]); //print vertex at the first line
        }
        System.out.printf("\n");
        for(i=0;i<GM.VertexNum;i++)
        {
            System.out.printf("%c", GM.Vertex[i]);
            for(j=0;j<GM.VertexNum;j++) 
            {
                if(GM.EdgeWeight[i][j]==GraphMatrix.MaxValue)
                {
                    System.out.printf("\tz");//z means infinity here
                }else
                {
                    System.out.printf("\t%d", GM.EdgeWeight[i][j]);
                }
            }System.out.printf("\n");
        }
    }
    
上一篇下一篇

猜你喜欢

热点阅读