package com.guge.test.graph;
/**
* 有向图
* Created by Guge on 2017/6/12.
*/
public class GraphD {
private int maxVerts;
private Vertex[] vertexList;
private int[][] adjMat;
private int nVerts;
private char[] sortedArray;
public GraphD(int size){
this.maxVerts=size;
vertexList=new Vertex[maxVerts];
adjMat=new int[maxVerts][maxVerts];
nVerts=0;
for (int i = 0; i < maxVerts; i++) {
for (int j = 0; j < maxVerts; j++) {
adjMat[i][j]=0;
}
}
sortedArray=new char[maxVerts];
}
public void addVertex(char label){
vertexList[nVerts++]=new Vertex(label);
}
public void addEdge(int start,int end){
adjMat[start][end]=1;
}
public void displayVertex(int v){
System.out.print(vertexList[v].label);
}
public int noSuccessors(){
boolean isEdge;
for (int i = 0; i <nVerts ; i++) {
isEdge=false;
for (int j = 0; j < nVerts; j++) {
if(adjMat[i][j]==1){
isEdge=true;
break;
}
}
if(!isEdge){
return i;
}
}
return -1;
}
/**
* 拓扑图
*/
public void topo(){
int orig_verts=nVerts;
while (nVerts>0){
int currentVerts=noSuccessors();
if(currentVerts==-1){
System.out.println("this is a cycle");
return;
}
sortedArray[nVerts-1]=vertexList[currentVerts].label;
deleteVertex(currentVerts);
}
for (int i = 0; i < orig_verts; i++) {
System.out.print(sortedArray[i]);
}
}
private void deleteVertex(int index){
if(index!=nVerts-1){
for (int i = index; i < nVerts-1; i++) {
vertexList[i]=vertexList[i+1];
}
for (int i = index; i < nVerts-1; i++) {
moveRowUp(i,nVerts);
}
for (int i = index; i <nVerts-1 ; i++) {
moveColLeft(i,nVerts-1);
}
}
nVerts--;
}
private void moveRowUp(int row,int length){
for (int col = 0; col <length ; col++) {
adjMat[row][col]=adjMat[row+1][col];
}
}
private void moveColLeft(int col,int length){
for (int row = 0; row <length ; row++) {
adjMat[row][col]=adjMat[row][col+1];
}
}
class Vertex{
public char label;
public boolean wasVisited;
public Vertex(char label){
this.label=label;
wasVisited=false;
}
}
}
class GraphDApp{
public static void main(String[] args) {
GraphD graph=new GraphD(20);
graph.addVertex('A');
graph.addVertex('B');
graph.addVertex('C');
graph.addVertex('D');
graph.addVertex('E');
graph.addVertex('F');
graph.addVertex('G');
graph.addVertex('H');
graph.addEdge(0,3); //AD
graph.addEdge(0,4); //AE
graph.addEdge(1,4); //BE
graph.addEdge(2,5); //CF
graph.addEdge(3,6); //DG
graph.addEdge(4,6); //EG
graph.addEdge(5,7); //FH
graph.addEdge(6,7); //GH
graph.topo();
}
}
java 有向图
最新推荐文章于 2024-01-25 07:30:00 发布