9024 week6 伪代码

伪代码

Array-of-edges Representation

Graph initialisation

newGraph(V):
| Input number of nodes V
| Output new empty graph
|
| g.nV = V // #vertices (numbered 0..V-1)
| g.nE = 0 // #edges
| allocate enough memory for g.edges[]
| return g

How much is enough? … No more than V(V-1)/2 … Much less in practice (sparse graph)

Edge insertion

insertEdge(g,(v,w)):
| Input graph g, edge (v,w)
|
| g.edges[g.nE]=(v,w)
| g.nE=g.nE+1
| g.nE=g.nE-1

Exercise #3: Array-of-edges Representation 27/83

Assuming an array-of-edges representation …
Write an algorithm to output all edges of the graph
answer:

show(g):
| Input graph g
|
| for all i=0 to g.nE-1 do
| print g.edges[i]
| end for

Time complexity: O(E)

Adjacency Matrix Representation

Graph initialisation

newGraph(V):
| Input number of nodes V
| Output new empty graph
|
| g.nV = V // #vertices (numbered 0..V-1) 
| g.nE = 0 // #edges
| allocate memory for g.edges[][]
| for all i,j=0..V-1 do
| g.edges[i][j]=0 // false
| end for
| return g

Edge insertion

insertEdge(g,(v,w)):
| Input graph g, edge (v,w)
|
| if g.edges[v][w]=0 then // (v,w) not in graph 
| g.edges[v][w]=1 // set to true
| g.edges[w][v]=1
| g.nE=g.nE+1
| end if

Edge removal

removeEdge(g,(v,w)):
| Input graph g, edge (v,w)
|
| if g.edges[v][w]≠0 then // (v,w) in graph 
| g.edges[v][w]=0 // set to false 
| g.edges[w][v]=0
| g.nE=g.nE-1
| end if

Exercise #4: Show Graph

Assuming an adjacency matrix representation ...
Write an algorithm to output all edges of the graph (no duplicates)

show(g):
| Input graph g
|
| for all i=0 to g.nV-2 do
| | for all j=i+1 to g.nV-1 do | | if g.edges[i][j] then
| | print i"—"j
| | end if
| | end for
| end for

Time complexity: O(V^2)

Exercise #5:

Analyse storage cost and time complexity of adjacency matrix representation
Storage cost: O(V^2)
If the graph is sparse, most storage is wasted.
Cost of operations:
initialisation: O(V^2) (initialise V×V matrix)
insert edge: O(1)(set two cells in matrix)
delete edge: O(1) (unset two cells in matrix)

Adjacency List Representation

Graph initialisation

newGraph(V):
| Input number of nodes V
| Output new empty graph
|
| g.nV = V // #vertices (numbered 0..V-1) 
| g.nE = 0 // #edges
| allocate memory for g.edges[]
| for all i=0..V-1 do
| g.edges[i]=NULL // empty list
| end for
| return g

Edge insertion:

insertEdge(g,(v,w)):
| Input graph g, edge (v,w) 
|
| insertLL(g.edges[v],w)
| insertLL(g.edges[w],v)
| g.nE=g.nE+1

Edge removal:

removeEdge(g,(v,w)):
| Input graph g, edge (v,w) 
|
| deleteLL(g.edges[v],w)
| deleteLL(g.edges[w],v)
| g.nE=g.nE-1

Exercise #7: Graph ADT Client

Write a program that uses the graph ADT to build the graph depicted below
50/83
print all the nodes that are incident to vertex 1 in ascending order


#include <stdio.h>
#include "Graph.h"
#define NODES 4
#define NODE_OF_INTEREST 1
int main(void) {
Graph g = newGraph(NODES);
   Edge e;
   e.v = 0; e.w = 1; insertEdge(g,e);
   e.v = 0; e.w = 3; insertEdge(g,e);
   e.v = 1; e.w = 3; insertEdge(g,e);
   e.v = 3; e.w = 2; insertEdge(g,e);
   int v;
   for (v = 0; v < NODES; v++) {
      if (adjacent(g, v, NODE_OF_INTEREST))
         printf("%d\n", v);
}
   freeGraph(g);
return 0; }

Graph ADT (Array of Edges)
Implementation of GraphRep (array-of-edges representation)

typedef struct GraphRep {
   Edge *edges; // array of edges
       int   nV;// #vertices (numbered 0..nV-1)
   int   nE;// #edges
   int   n;// size of edge array
} GraphRep;

Graph ADT (Adjacency Matrix)
Implementation of GraphRep (adjacency-matrix representation)

typedef struct GraphRep {
   int  **edges; // adjacency matrix
   int    nV;    // #vertices
   int    nE;    // #edges
} GraphRep;

Implementation of graph initialisation (adjacency-matrix representation)

Graph newGraph(int V) {
   assert(V >= 0);
    int i;
   Graph g = malloc(sizeof(GraphRep));
   g->nV = V;  g->nE = 0;
   // allocate memory for each row
   g->edges = malloc(V * sizeof(int *));
   // allocate memory for each column and initialise with 0
   for (i = 0; i < V; i++) {
      g->edges[i] = calloc(V, sizeof(int)); 
      assert(g->edges[i] != NULL);
   }
return g; 
}

standard library function calloc(size_t nelems, size_t nbytes) allocates a memory block of size nelems*nbytes and sets all bytes in that block to zero

Implementation of edge insertion/removal (adjacency-matrix representation)

// check if vertex is valid in a graph
bool validV(Graph g, Vertex v) {
   return (g != NULL && v >= 0 && v < g->nV);
}
void insertEdge(Graph g, Edge e) {
   assert(g != NULL && validV(g,e.v) && validV(g,e.w));
   if (!g->edges[e.v][e.w]) {  // edge e not in graph
      g->edges[e.v][e.w] = 1;
      g->edges[e.w][e.v] = 1;
      g->nE++;
} }
void removeEdge(Graph g, Edge e) {
   assert(g != NULL && validV(g,e.v) && validV(g,e.w));
   if (g->edges[e.v][e.w]) {   // edge e in graph
      g->edges[e.v][e.w] = 0;
      g->edges[e.w][e.v] = 0;
      g->nE--;
} }

Exercise #8: Checking Neighbours (i)

Graph ADT (Adjacency List)
Implementation of GraphRep (adjacency-list representation)

typedef struct GraphRep {
   Node **edges;  // array of lists
   int    nV;     // #vertices
   int    nE;     // #edges
} GraphRep;
typedef struct Node {
   Vertex       v;
   struct Node *next;
} Node;

Exercise #9: Checking Neighbours (ii)

Depth-first Search

Recursive DFS path checking

hasPath(G,src,dest):
| Input graph G, vertices src,dest
| Output true if there is a path from src to dest in G, | false otherwise
|
| return dfsPathCheck(G,src,dest)

dfsPathCheck(G,v,dest):
 | mark v as visited
| if v=dest then // found dest
| return true
| else
| | for all (v,w)∈edges(G) do
| | | if w has not been visited then
| | | return dfsPathCheck(G,w,dest) // found path via w to dest | | | end if
| | end for
| end if
| return false // no path from v to dest
visited[] // store previously visited node, for each vertex 0..nV-1
findPath(G,src,dest):
| Input graph G, vertices src,dest
|
| for all vertices v∈G do
| visited[v]=-1
| end for
| visited[src]=src
| if dfsPathCheck(G,src,dest) then // show path in dest..src order | | v=dest
                                // found edge from v to dest
| |
| |
| |
| | end while | | print src | end if
while v≠src do print v"-"
v=visited[v]
dfsPathCheck(G,v,dest):
| if v=dest then  // found edge from v to dest
| return true
| else
| | for all (v,w)∈edges(G) do | | | if visited[w]=-1 then | | | | visited[w]=v
| | | | if dfsPathCheck(G,w,dest) then
| | | | return true | | | | end if
| | | end if
| | end for
| end if
| return false // no path from v to dest

DFS can also be described non-recursively (via a stack):

hasPath(G,src,dest):
| Input graph G, vertices src,dest
| Output true if there is a path from src to dest in G, 
| false otherwise
|
| push src onto new stack s
| found=false
| while not found and s is not empty do
| | pop v from s
| | mark v as visited
| | if v=dest then
| | found=true
| | else
| | | for each (v,w)∈edges(G) such that w has not been visited
| | | push w onto s | | | end for
| | end if
| end while
| return found

Uses standard stack operations (push, pop, check if empty)
Time complexity is the same: O(V+E) (each vertex added to stack once, each element in vertex's adjacency list visited once)

Breadth-first Search

visited[] // array of visiting orders, indexed by vertex 0..nV-1
findPathBFS(G,src,dest):
| Input graph G, vertices src,dest
|
| for all vertices v∈G do
| visited[v]=-1
| end for
| enqueue src into new queue q
| visited[src]=src
| found=false
| while not found and q is not empty do
| | dequeue v from q
| | if v=dest then
| | found=true
| | else
| | | for each (v,w)∈edges(G) such that visited[w]=-1 do enqueue w into q
| | | visited[w]=v
| | | end for
| | end if
| end while
| if found then
| display path in dest..src order | end if
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,324评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,303评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,192评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,555评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,569评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,566评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,927评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,583评论 0 257
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,827评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,590评论 2 320
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,669评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,365评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,941评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,928评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,159评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,880评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,399评论 2 342

推荐阅读更多精彩内容

  • 小学高年级学生的“四大关口” 许多家长带着上小学的孩子前来咨询,几乎是同一类型的问题。 这就是不好好学习,上课不注...
    舒言2017阅读 658评论 3 1
  • 我 在等一场挽救 我捧着心 站在风中 看百花凋谢 怎一场残酷的坠落 无人问津的山林与沟壑 无人涉足的丘陵与陡坡 就...
    伦小让阅读 137评论 0 2
  • "目录号: HY-13955 GPCR/G ProteinAutophagy- Telmisartan 是一种有效...
    莫小枫阅读 622评论 0 0
  • 小处不慎漏,暗处不欺隐,末路不怠慌。 当怒火预水正腾沸时,明明知得,又明明犯著。知得是谁,犯著又是谁,此处能猛然转...
    HedyWang1阅读 107评论 0 0