1. 程式人生 > >[圖] 0 總結 - 記憶版

[圖] 0 總結 - 記憶版

文章目錄

基本操作

CreateGraph(&G, v, VR) //按定義(v,VR)構造圖
DestroyGraph(&G) //銷燬圖
LocateVex(G, u) //返回u的位置
GetVex(G, v) //返回v的值
PutVex(&G, v, value) //賦值
FirstAdjVex(G, v) //v的第一個鄰邊
NextAdjVex(G, v, w) //v相對於w的下一個鄰接點
InsertVex(&G, v) //新頂點v DeleteVex(&G, v) //刪除v和相關弧 InsertArc(&G, v, w) //新增弧v,w DeleteArc(&G, v, w) //刪除 DFSTraverse(G, v, Visit()) BFSTraverse(G, v, Visit())

儲存結構

鄰接矩陣

//簡單版
char vertex[5] = {'A','B','C','D','E'}; //頂點資訊
float Edge[5][5]; //邊
for (int i=0; i<5; ++i)
	for (int j=0; j<5
; ++j) Edge[i][j] = MAX; // 嚴書 typedef struct ArcCell { // 弧的定義 VRType adj; // VRType是頂點關係型別 // 對無權圖,用1或0表示相鄰否; // 對帶權圖,則為權值型別。 InfoType *info; // 該弧相關資訊的指標 } ArcCell, AdjMatrix[MAX_VERTEX_NUM][MAX_VERTEX_NUM]; typedef struct { // 圖的定義 VertexType vexs[MAX_VERTEX_NUM]
; // 頂點資訊 AdjMatrix arcs; // 弧的資訊 int vexnum, arcnum; // 頂點數,弧數 GraphKind kind; // 圖的種類標誌 } MGraph;

鄰接表

typedef struct ArcNode{
	int adjV; //這條邊所指的頂點
	struct ArcNode *next; //指向下一個邊
}ArcNode; //邊
typedef struct{
	int data;  // 頂點資訊
	ArcNode* first; // 指向第一條依附該頂點的弧
}VNode,AdjList[MAX_VERTEX_NUM]; //頂點
typedef struct{
	AdjList vertices;
	int vexnum, arcnum;
	int kind; //圖的種類
}ALGraph; //圖

有向圖的十字連結串列

//邊 start->end
typedef struct ArcBox {
	int headvex; //弧的頭
	int tailvex; //弧的尾
	struct ArcBox *hlink; //headvex的下一條出邊
    struct ArcBox  *tlink; //tlink下一條入邊
}ArcNode; //弧的結構表示
typedef struct VexNode { 
	VertexType  data;
	ArcBox  *firstin; //第一個入邊
	ArcBox *firstout; //第一個出邊
}VexNode; // 頂點的結構表示
typedef struct { 
	VexNode  xlist[MAX_VERTEX_NUM]; // 頂點結點
	int	vexnum; //當前頂點樹
	int arcnum; //弧數
}OLGraph; //有向圖十字連結串列

無向圖的鄰接多重表

//邊i-j
typedef struct EBox { //
	VisitIf       mark; // 訪問標記
	InfoType     *info; //資訊指標   
	int ivex; //i結點
	struct EBox* inext; //i結點的下一條邊
	int jvex; //j結點
	struct EBox* jnext; //j結點的下一條邊
}EBox;
//頂點
typedef struct VexBox {
   VertexType  data;
   EBox  *first; //該結點的第一條邊
}VexBox;
//鄰接多重表
typedef struct {
    VexBox  adjmulist[MAX_VERTEX_NUM];
    int   vexnum, edgenum; //頂點數、邊樹    
} AMLGraph;

遍歷

// DFS
int visit[maxSize];
void DFSUtil(Graph G, int v) {
	int w;
	// 訪問
	visit[v] = 1;
	Visit( GetVex(G, v) );
	// 遍歷鄰邊
	for (w=FirstAdjVex(G, v); w!=-1; w=NextAdjVex(G, v,w) ) {
		if (visit[w]!=1) {
			DFSUtil(G, w);
		}
	}
}
void DFS(Graph G) {
	int v;
	for (v=1; v<=G.n; v++) {
		if (visit[v]==0) DFSUtil(G, v);
	}
}
// BFS
int visit[maxSize];
void BFSUtil(Graph G, int v) {
	int queue[maxSize],front,rear;
	int w;
	front=rear=0;
	visit[v] = 1; Visit( GetVex(G, v) ); // 訪問
	queue[rear] = v;rear = (rear+1)%maxSize; // 放入佇列
	while (front!=rear) {
		v=queue[front]; front=(front+1)%maxSize;
		for (w=FirstAdjVex(G, v); w!=-1; w=NextAdjVex(G, v, w)) {
			if (visit[w]==0) {
				visit[w]=1; Visit( GetVex(G, v) ); //訪問
				queue[rear]=w; rear=(rear+1)%maxSize;
			}
		}
	}
}
void BFS(Graph G) {
	int v;
	for (v=1; v<=G.n; v++) {
		if (visit[v]==0)
			BFSUtil(G, v);
	}
}