package coding;
import java.util.Scanner;
import javax.swing.plaf.synth.SynthSeparatorUI;
class GraphMatrix{
static final int MaxNum=20 ;
static final int MaxValue=65535 ;
char [] Vertex=new char [MaxNum];
int GType;
int VertexNum;
int EdgeNum;
int [][] EdgeWeight=new int [MaxNum][MaxNum];
int [] isTrav=new int [MaxNum];
}
public class cha02_Graph {
static Scanner input=new Scanner(System.in );
static void CreateGraph(GraphMatrix GM){
int i,j ,k;
int weight;
char EstartV,EendV;
System.out .printf("输入图中各顶点信息:" );
for (i=0 ;i<GM.VertexNum;i++){
System.out .printf("第%d个顶点" ,i+1 );
GM.Vertex[i]=(input.next().toCharArray()[0 ]);
}
System.out .println("输入构成各边的顶点:" );
for (k=0 ;k<GM.EdgeNum;k++){
System.out .printf("第%d条边" ,k+1 );
EstartV=input.next().charAt(0 );
EendV=input.next().charAt(0 );
weight=input.nextInt();
for (i=0 ;EstartV!=GM.Vertex[i];i++);
for (j=0 ;EendV!=GM.Vertex[j];j++);
GM.EdgeWeight[j][i]=weight;
if (GM.GType==0 ){
GM.EdgeWeight[j][i]=weight;
}
}
}
static 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]=GraphMatrix.MaxValue;
}
}
}
static void OutGraph(GraphMatrix GM){
int i,j;
for (j=0 ;j<GM.VertexNum;j++){
System.out .printf("\t%c" ,GM.Vertex[j]);
}
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" );
}
else {
System.out .printf("\t%d" ,GM.EdgeWeight[i][j]);
}
}System.out .printf("\n" );
}
}
static void DeepTraOne(GraphMatrix GM,int n){
int i;
GM.isTrav[n]=1 ;
System.out .printf("->%c" ,GM.Vertex[n]);
for (i=0 ;i<GM.VertexNum;i++){
if (GM.EdgeWeight[n][i]!=GraphMatrix.MaxValue&&GM.isTrav[n]==0 ){
DeepTraOne(GM,i);
}
}
}
static void DeepTraGraph(GraphMatrix GM){
int i;
for (i=0 ;i<GM.VertexNum;i++){
GM.isTrav[i]=0 ;
}
System.out .printf("深度优先遍历节点" );
for (i=0 ;i<GM.VertexNum;i++){
if (GM.isTrav[i]==0 ){
DeepTraOne(GM,i);
}
}System.out .printf("\n" );
}
public static void main(String[] args) {
GraphMatrix GM=new GraphMatrix();
System.out .println("输入生成的类型:" );
GM.GType=input.nextInt();
System.out .println("输入图的顶点数:" );
GM.VertexNum=input.nextInt();
System.out .println("输入图的边数量:" );
GM.EdgeNum=input.nextInt();
ClearGraph(GM);
CreateGraph(GM);
System.out .println("该图的邻接矩阵数据如下:" );
OutGraph(GM);
DeepTraGraph(GM);
}
}