CHAPTER 29 Elementary Graph Algorithms int V, E; int a[maxV][maxV]; void adjmatrix() { int j, x, y; cin >> V >> E; for (x = 1; x <= V; x++) for (y = 1; y <= V; y++) a[x][y] = 0; for (x = 1; x <= V; x++) a[x][x] = 1; for (j = 1; j <= E; j++) { cin >> v1 >> v2; x = index(v1); y = index(v2); a[x][y] = 1; a[y][x] = 1; } } struct node { int v; struct node *next; }; int V, E; struct node *adj[maxV], *z; void adjlist() { int j, x, y; struct node *t; cin >> V >> E; z = new node; z->next = z; for (j = 1; j <= V; j++) adj[j] = z; for (j = 1; j <= E; j++) { cin >> v1 >> v2; x = index(v1); y = index(v2); t = new node; t->v = x; t->next = adj[y]; adj[y] = t; t = new node; t->v = y; t->next = adj[x]; adj[x] = t; } } void search() { int k; for (k = 1; k <= V; k++) val[k] = unseen; for (k = 1; k <= V; k++) if (val[k] == unseen) visit(k); } void visit(int k) // DFS, adjacency lists { struct node *t; val[k] = ++id; for (t = adj[k]; t != z; t = t->next) if (val[t->v] == unseen) visit(t->v); } void visit(int k) // DFS, adjacency matrix { int t; val[k] = ++id; for (t = 1; t <= V; t++) if (a[k][t] != 0) if (val[t] == unseen) visit(t); } Stack stack(maxV); void visit(int k) // non-recursive DFS, adj lists { struct node *t; stack.push(k); while (!stack.empty()) { k = stack.pop(); val[k] = ++id; for (t = adj[k]; t != z; t = t->next) if (val[t->v] == unseen) { stack.push(t->v); val[t->v] = -1; } } } Queue queue(maxV); void visit(int k) // BFS, adjacency lists { struct node *t; queue.put(k); while (!queue.empty()) { k = queue.get(); val[k] = ++id; for (t = adj[k]; t != z; t = t->next) if (val[t->v] == unseen) { queue.put(t->v); val[t->v] = -1; } } }