Chapter 16: Graphs and Digraphs

Size: px
Start display at page:

Download "Chapter 16: Graphs and Digraphs"

Transcription

1 Chapter 16: Graphs and Digraphs Exercises adj: 2. adj: 3. adj: 4. adj: 5. E A B 1 2 data: data: B BE data: BEA BEAR BEARD cat zebra horse data: rat bear dog D C 308

2 6. CAT DOG RAT BAT Alpha Tho Beta Pi Gamma Mu Delta 309

3

4

5

6

7

8 A 123 D B C cat cat dog rat dog rat cat Al dog rat Rob Bob Nan Dot Mo 315

9 Exercises Step v w Visit 2. Step v w Visit Step v Visit Queue 4. Step v Visit Queue 1, , a 1 3a 2 3b b a 2 4 3a 1 3 3b b a 4 3 3a 3 4 3b 4 3 3b 3 4 3a 3 3a 4 3b 3 3b 4 5. Step v distance Queue Labels for: ,2, p[2] = 4, p[1] = 1, p[0] = 2 6. Step v w Visit 7. Step v w Visit 1 cat cat 1 zebra zebra 2 cat zebra 2 zebra horse 1 zebra zebra 1 horse horse 2 zebra horse 2 horse 1 horse horse 2 horse 1 rat rat 2 rat bear 1 bear bear 2 bear 1 dog dog 2 dog 316

10 8. Step v Visit Queue 1,2 cat cat 3a cat 3b cat zebra, rat, dog zebra rat dog 3a zebra rat dog 3b zebra horse rat dog horse 3a rat dog horse 3b rat bear dog horse bear 3a dog horse bear 3b dog horse bear 3a horse bear 3b horse bear 3a bear 3b bear 9. Step v Visit Queue 1,2 zebra zebra 3a zebra 3b zebra horse horse 3a horse 3b horse 10. Step v distance Queue Labels for: cat zebra horse rat bear dog 1,2,3 0 rat 0 4 rat 0 cat horse bear cat 1 zebra dog p[2] = dog, p[1] = cat, p[0] = rat 317

11 11. Step v w Visit 12. Step v w Visit 1 A A 1 F F 2 A B 2 F J 1 B B 1 J J 2 B C 2 J K 1 C C 1 K K 2 C E 2 K I 1 E E 1 I I 2 E F 2 I 1 F F 2 F J 1 J J 2 J K 1 K K 2 K I 1 I I 2 I 1 G G 2 G H 1 H H 2 H 1 D D 2 D 13. Step v Visit Queue 14. Step v Visit Queue 1,2 A A 1,2 F F 3a A 3a F 3b A B D B D 3b F J J 3a B D 3a J 3b B C D C 3b J K K 3a D C 3a K 3b D C 3b K I I 3a C 3a I 3b C E F E F 3b I 3a E F 3b E G I F G I 3a F G I 3b F J G I J 3a G I J 3b G H I J H 3a I J H 3b I J H 3a J H 3b J K H K 3a H K 3b H K 3a K 3b K 318

12 15. Step v distance Queue Labels for: A B C D E F G H I J K 1,2,3 0 A 0 4 A 0 B D B 1 D C D 1 C D 2 EF p[3] = E, p[2] = C, p[1] = B, p[0] = A 16. Step v distance Queue Labels for: A B C D E F G H I J K 1,2,3 0 A 0 4 A 0 B D B 1 D C D 1 C C 2 E F E 3 F G I F 3 G I J G 4 I J H p[5] = H, p[4] = G, p[3] = E, p[2] = C, p[1] = B, p[0] = A 17. Step v distance Queue Labels for: A B C D E F G H I J K 1,2,3 0 G 0 4 G 0 H I H 1 I A E I 1 A E J A 2 E J B D E 2 J B D F J 2 B D F K B 3 D F K C p[4] = C, p[3] = B, p[2] = A, p[1] = H, p[0] = G 18. Step v distance Queue Labels for: A B C D E F G H I J K 1,2,3 0 J 0 4 J 0 K K 1 I p[2] = I, p[1] = K, p[0] = J 319

13 19. Step v distance Queue Labels for: A B C D E F G H I J K 1,2,3 0 J 0 4 J 0 K K 1 I I 2 empty 5 No such path 20. #include <queue> // Put prototype in public section of class template Digraph void breadthfirstsearch(int start); /* Breadth-first search of digraph, starting at vertex start. Uses a Queue class template to store vertices. Precondition: start is a vertex. Postcondition: Digraph has been breadth-first searched from start */ // Put definition in Digraph.h below the class declaration template <typename DataType> void Digraph<DataType>::breadthFirstSearch(int start) { // Process v[start].data here cout << myadjacencylists[start].data << endl; queue<vertexinfo> q; q.enqueue(myadjacencylists[start]); vector<bool> unvisited(myadjacencylists.size(), true); while (!q.empty()) { VertexInfo v = q.front(); q.dequeue(); for (list<int>::iterator it = v[start].adjacencylist.begin(); it!= v[start].adjacencylist.end(); it++) if (unvisited[*it]) { // process *it here cout << (*it).data << endl; } } } unvisited[(*it).data] = false; q.enqueue(*it); 320

14 21. Matrix multiplication and addition can be used to find the reachability matrix from a digraph's adjacency matrix. In the following, the type Matrix is defined by statements like the following (or preferably, a class with built-in operations): const int MAX_SIZE =... // max # rows/columns + 1 typedef int Matrix[MAX_SIZE][MAX_SIZE]; /* Function to find reachability matrix of a digraph from its n x n adjacency matrix adj. Receive: Adjacency matrix adj Return: Reachability matrix */ findreach(matrix adj, int n, Matrix reach) { Matrix ident; makeidentity(n, ident); } Matrix sum, // cumulative sum of powers of adj power, // a power of adj prod, // used to find adj X power reach; // reachability matrix copymatrix(ident, prod); for (int count = 1; count < n; count++) { findproduct(a, prod, power); findsum(reach, power, sum); copy(power, prod); copy(sum, reach); } The following functions can be used for the matrix operations: // Create n x n identity matrix ident void makeidentity(int n, Matrix ident) { for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) ident[i][j] = 0; for (int i = 1; i <= n; i++) ident[i][i] = 1; } // Copy n x n matrix mat into matrix copy void copymatrix(int n, Matrix mat, Matrix copy) { for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) copy[i][j] = mat[i][j]; } 321

15 // Find sum of n x nmatrices mat1 and mat2. Matrix findsum(matrix mat1, Matrix mat2, int n, Matrix sum) { for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) sum[i][j] = mat1[i][j] + mat2[i][j]; } // Find product of n x n matrices mat1 and mat2. Matrix findproduct(matrix mat1, Matrix mat2, int n, Matrix prod) { for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) { int sum = 1; for (int k = 1; k <= n; k++) sum += mat1[i][k] * mat2[k][j]; prod[i][j] = sum; } } 22. This is a simple modification of the solution in Exercise 21. Use && instead of * and instead of multiply (*) in the matrix functions /* Function to find reachability matrix of a digraph from its n x n adjacency matrix adj using Warshall's algorithm Receive: Adjacency matrix adj Return: Reachability matrix */ findreach(matrix adj, int n, Matrix reach) { Matrix reach; copymatrix(adj, reach); int k = 1; 322

16 } while (k <= n &&!allones(reach)) { for (int i = 1; i <= n && i!= k; i++) if (reach[i][k]!= q for (int j = 1; j <= n, j++) reach[i][j] = reach[k][j]; k++ } //-- Check if matrix mat contains all 1s bool allones(matrix mat) { for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) if (mat[i][j]!= 1) return false; return true; } Exercises adj: 2. adj: 3. adj: data: data: B BE data: BEA BEAR BEARD 323

17 4. adj: moose zebra horse data: rat bear dog cow

18

19

20

21

22

23 e e4 e3 e1 2 e2 3 1 e3 e2 e1 4 e5 2 e4 e e e11 e7 1 e5 e2 e1 e3 2 e4 3 e8 e6 5 e

24 A1 cat 1 A1 4D 2B cow 5 dog 2 C2 3B C3 bat 4 rat A1 ) A1 (f) Al C2 3B C2 3B Rob Bob Nan Dot Mo

25

26 32. Note: The following algorithms assume the adjacency list representation of a graph. 33. Algorithm to insert a new vertex and its connecting edges into a graph: 1. Get a new head node. 2. Search the array v to find the first v[k] that is null, and set v[k] to point to this new head node. //-- Assume all elements of v are initialized to null pointers. 3. Set the data field of the head node to the given item. 4. For each vertex adjacent to the new vertex (as entered by the user): a. Add a new node for the adjacent vertex to the new vertex list,x. b. Add a new node for the new vertex to the list for the adjacent vertex. End for. 333

27 34. Algorithm to search for a vertex containing a given data item: Simply search the array v for a head node containing the data item. 35. Algorithm to delete a given data item and all edges incident to it: 1. Find the location k in the array v of the head node containing the data item; if it is not found, terminate this algorithm and display an appropriate message. 2. Set ptr = v[k]->next. 3. While (ptr!= 0), do the following: a. Search the list pointed to by v[ptr->vertex] for the node that contains the given data item and delete this node from the list. b. Set ptr = ptr ->next. 4. Delete the entire list at v[k] and make v[k] a null pointer. 36. Algorithm to find all vertices adjacent to a given vertex: 1. Find the location k in the array v of the head node containing the data item; if it is not found, terminate this algorithm and display an appropriate message. 2.Set ptr = v[k]->next. 3.While (ptr!= 0), do the following: a. Process v[ptr ->vertex], which is one of the adjacent vertices. b. Set ptr = ptr ->next. End while. 37. One method of determining if a graph (with adjacency matrix A) has a cycle follows: 1. Multiply A times itself (producing matrix A 2 ). 2. Set i = 2 and done = false. 3. While (! done), do the following: a. Multiply A times itself. b. If the diagonal of A has a non-zero entry, or i = number of vertices in the graph, Set done = true. Else Increment i by 1. End if End while. 334

28 38. One way to find a spanning tree is to do a depth-first traversal of the graph. This is a simple modification of the depthfirstsearch() function member of the class Graph in Figure 16.4 of the text. Simply add another parameter vector<bool> & edgelist and on each recursive call, inside the while loop, add the edge pointed to by ptr to edgelist. 39. Kruskal's algorithm is a simple modification of the spanning-tree function in Exercise 38 where one selects at each step the cheapest candidate for an edge. To do the selections most efficiently, store the edge nodes in a priority queue with the highest priority edges being those with minimal cost. 335

Graphs. directed and undirected graphs weighted graphs adjacency matrices. abstract data type adjacency list adjacency matrix

Graphs. directed and undirected graphs weighted graphs adjacency matrices. abstract data type adjacency list adjacency matrix Graphs 1 Graphs directed and undirected graphs weighted graphs adjacency matrices 2 Graph Representations abstract data type adjacency list adjacency matrix 3 Graph Implementations adjacency matrix adjacency

More information

Graphs & Digraphs Tuesday, November 06, 2007

Graphs & Digraphs Tuesday, November 06, 2007 Graphs & Digraphs Tuesday, November 06, 2007 10:34 PM 16.1 Directed Graphs (digraphs) like a tree but w/ no root node & no guarantee of paths between nodes consists of: nodes/vertices - a set of elements

More information

CSCE 110 PROGRAMMING FUNDAMENTALS

CSCE 110 PROGRAMMING FUNDAMENTALS CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class Prof. amr Goneid, AUC 1 Dictionaries(1): A Key Table Class Prof. Amr Goneid, AUC 2 A Key Table

More information

Chapter 12: Searching: Binary Trees and Hash Tables. Exercises 12.1

Chapter 12: Searching: Binary Trees and Hash Tables. Exercises 12.1 Chapter 12: Searching: Binary Trees and Hash Tables Exercises 12.1 1. 4, 6 2. 4, 1, 2, 3 3. 4, 6, 5 4. 4, 1, 0 5. 4, 6, 7, 8 6. template linearsearch(elementtype x[], ElementType

More information

Graph Search Methods. Graph Search Methods

Graph Search Methods. Graph Search Methods Graph Search Methods A vertex u is reachable from vertex v iff there is a path from v to u. 0 Graph Search Methods A search method starts at a given vertex v and visits/labels/marks every vertex that is

More information

Implementing Algorithms

Implementing Algorithms Implementing Algorithms 1 Data Structures implementing algorithms arrays and linked lists 2 Implementing the Gale-Shapley algorithm selecting data structures overview of the selected data structures 3

More information

13.4 Case Study: vector<t>-based Matrices

13.4 Case Study: vector<t>-based Matrices 13.4 Case Study: vector-based Matrices 1 13.4 Case Study: vector-based Matrices A two-dimensional numeric array having m rows and n columns is called an m n matrix. There are many important applications

More information

1. Mother vertex using BFS. A mother vertex in a graph G = (V,E) is a vertex v such that all other vertices in G can be reached by a path from v.

1. Mother vertex using BFS. A mother vertex in a graph G = (V,E) is a vertex v such that all other vertices in G can be reached by a path from v. Design and Analysis of Algorithms Assignment(September 5 th 2017) Solutions (Hints) REMARK: The codes given below are just a guide, this is not the only way to write programs for these algorithms. What

More information

Graphs. The ultimate data structure. graphs 1

Graphs. The ultimate data structure. graphs 1 Graphs The ultimate data structure graphs 1 Definition of graph Non-linear data structure consisting of nodes & links between them (like trees in this sense) Unlike trees, graph nodes may be completely

More information

CS490: Problem Solving in Computer Science Lecture 6: Introductory Graph Theory

CS490: Problem Solving in Computer Science Lecture 6: Introductory Graph Theory CS490: Problem Solving in Computer Science Lecture 6: Introductory Graph Theory Dustin Tseng Mike Li Wednesday January 16, 2006 Dustin Tseng Mike Li: CS490: Problem Solving in Computer Science, Lecture

More information

This course is intended for 3rd and/or 4th year undergraduate majors in Computer Science.

This course is intended for 3rd and/or 4th year undergraduate majors in Computer Science. Lecture 9 Graphs This course is intended for 3rd and/or 4th year undergraduate majors in Computer Science. You need to be familiar with the design and use of basic data structures such as Lists, Stacks,

More information

Graph Search Methods. Graph Search Methods

Graph Search Methods. Graph Search Methods Graph Search Methods A vertex u is reachable from vertex v iff there is a path from v to u. 0 Graph Search Methods A search method starts at a given vertex v and visits/labels/marks every vertex that is

More information

CISC 3150 Sample Final Exam

CISC 3150 Sample Final Exam CISC 3150 Sample Final Exam Question 1: Trace the program and give the output for parts (a) through (d). #include using namespace std; class basecl public: basecl(): databcl(5) void output()

More information

lecture27: Graph Traversals

lecture27: Graph Traversals lecture27: Largely based on slides by Cinda Heeren CS 225 UIUC 25th July, 2013 Announcements mp7.1 extra credit due tomorrow night (7/26) Code challenge tomorrow night (7/26) at 6pm in 0224 lab hash due

More information

Test 1: CPS 100. Owen Astrachan. February 23, 2000

Test 1: CPS 100. Owen Astrachan. February 23, 2000 Test 1: CPS 100 Owen Astrachan February 23, 2000 Name: Login: Honor code acknowledgment (signature) Problem 1 value 19 pts. grade Problem 2 24 pts. Problem 3 8 pts. Problem 4 9 pts. Problem 5 6 pts. TOTAL:

More information

A6-R3: DATA STRUCTURE THROUGH C LANGUAGE

A6-R3: DATA STRUCTURE THROUGH C LANGUAGE A6-R3: DATA STRUCTURE THROUGH C LANGUAGE NOTE: 1. There are TWO PARTS in this Module/Paper. PART ONE contains FOUR questions and PART TWO contains FIVE questions. 2. PART ONE is to be answered in the TEAR-OFF

More information

Draw the resulting binary search tree. Be sure to show intermediate steps for partial credit (in case your final tree is incorrect).

Draw the resulting binary search tree. Be sure to show intermediate steps for partial credit (in case your final tree is incorrect). Problem 1. Binary Search Trees (36 points) a) (12 points) Assume that the following numbers are inserted into an (initially empty) binary search tree in the order shown below (from left to right): 42 36

More information

moretosearch = (location < length);

moretosearch = (location < length); Chapter 3(6th edition): Exercises 1,2,3,9,10,11,12,18-28 (due: 25/10/2017) Solution: 1. (a) Boolean IsThere(ItemType item) Function: Determines if item is in the list. Precondition: List has been initialized.

More information

Unweighted Graphs & Algorithms

Unweighted Graphs & Algorithms Unweighted Graphs & Algorithms Zachary Friggstad Programming Club Meeting References Chapter 4: Graph (Section 4.2) Chapter 22: Elementary Graph Algorithms Graphs Features: vertices/nodes/dots and edges/links/lines

More information

Section 1: True / False (2 points each, 30 pts total)

Section 1: True / False (2 points each, 30 pts total) Section 1: True / False (2 points each, 30 pts total) Circle the word TRUE or the word FALSE. If neither is circled, both are circled, or it impossible to tell which is circled, your answer will be considered

More information

1. Graph and Representation

1. Graph and Representation Chapter Graphs Tree Root Direction: parent-child relationships No cycles Graph Vertices + Edges No tree restrictions Examples World Wide Web Maps. Graph and Representation A graph G: a pair (V, E) vertices

More information

Linked List using a Sentinel

Linked List using a Sentinel Linked List using a Sentinel Linked List.h / Linked List.h Using a sentinel for search Created by Enoch Hwang on 2/1/10. Copyright 2010 La Sierra University. All rights reserved. / #include

More information

Pointers, Dynamic Data, and Reference Types

Pointers, Dynamic Data, and Reference Types Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation The new operator The delete operator Dynamic Memory Allocation for Arrays 1 C++ Data Types simple

More information

CS 2412 Data Structures. Chapter 9 Graphs

CS 2412 Data Structures. Chapter 9 Graphs CS 2412 Data Structures Chapter 9 Graphs Some concepts A graph consists of a set of vertices and a set of lines (edges, arcs). A directed graph, or digraph, is a graph in which each line has a direction.

More information

CSE 100: GRAPH ALGORITHMS

CSE 100: GRAPH ALGORITHMS CSE 100: GRAPH ALGORITHMS 2 Graphs: Example A directed graph V5 V = { V = E = { E Path: 3 Graphs: Definitions A directed graph V5 V6 A graph G = (V,E) consists of a set of vertices V and a set of edges

More information

Abstract Data Types 1

Abstract Data Types 1 Abstract Data Types 1 Purpose Abstract Data Types (ADTs) Lists Stacks Queues 2 Abstract Data Types (ADTs) ADT is a set of objects together with a set of operations. Abstract in that implementation of operations

More information

SELF-BALANCING SEARCH TREES. Chapter 11

SELF-BALANCING SEARCH TREES. Chapter 11 SELF-BALANCING SEARCH TREES Chapter 11 Tree Balance and Rotation Section 11.1 Algorithm for Rotation BTNode root = left right = data = 10 BTNode = left right = data = 20 BTNode NULL = left right = NULL

More information

CS 206 Introduction to Computer Science II

CS 206 Introduction to Computer Science II CS 206 Introduction to Computer Science II 04 / 06 / 2018 Instructor: Michael Eckmann Today s Topics Questions? Comments? Graphs Definition Terminology two ways to represent edges in implementation traversals

More information

Intermediate Programming, Spring 2017*

Intermediate Programming, Spring 2017* 600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general

More information

CS302 - Data Structures using C++

CS302 - Data Structures using C++ CS302 - Data Structures using C++ Topic: Graphs - Introduction Kostas Alexis Terminology In the context of our course, graphs represent relations among data items G = {V,E} A graph is a set of vertices

More information

L10 Graphs. Alice E. Fischer. April Alice E. Fischer L10 Graphs... 1/37 April / 37

L10 Graphs. Alice E. Fischer. April Alice E. Fischer L10 Graphs... 1/37 April / 37 L10 Graphs lice. Fischer pril 2016 lice. Fischer L10 Graphs... 1/37 pril 2016 1 / 37 Outline 1 Graphs efinition Graph pplications Graph Representations 2 Graph Implementation 3 Graph lgorithms Sorting

More information

Final Exam Questions Study Guide (Draft!)

Final Exam Questions Study Guide (Draft!) Final Exam Questions Study Guide (Draft!) These questions are for review only and are not calibrated for time! [2-3 Tree]: Given the following 2-3 tree declaration, implement the insert_right() function.

More information

Homework 6 Solutions CS330 Discrete Structures, Fall 2017

Homework 6 Solutions CS330 Discrete Structures, Fall 2017 Homework 6 Solutions CS330 Discrete Structures, Fall 2017 Instructor: Professor Edward Reingold TA: Jiahui Hou, Haohua Du Solutions 1. 10 pts) Algorithm 1 Basic Euler Circuit Algorithm. procedure Euler(G

More information

This examination has 11 pages. Check that you have a complete paper.

This examination has 11 pages. Check that you have a complete paper. MARKING KEY The University of British Columbia MARKING KEY Computer Science 252 2nd Midterm Exam 6:30 PM, Monday, November 8, 2004 Instructors: K. Booth & N. Hutchinson Time: 90 minutes Total marks: 90

More information

the Queue queue ADT using the STL queue designing the simulation simulation with STL queue using STL list as queue using STL vector as queue

the Queue queue ADT using the STL queue designing the simulation simulation with STL queue using STL list as queue using STL vector as queue the Queue 1 The Queue Abstract Data Type queue ADT using the STL queue 2 Simulating a Printer Queue designing the simulation simulation with STL queue 3 adapting STL list and vector using STL list as queue

More information

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College November 22, 2017 Outline Outline 1 Chapter 12: C++ Templates Outline Chapter 12: C++ Templates 1 Chapter 12: C++ Templates

More information

11/22/2016. Chapter 9 Graph Algorithms. Introduction. Definitions. Definitions. Definitions. Definitions

11/22/2016. Chapter 9 Graph Algorithms. Introduction. Definitions. Definitions. Definitions. Definitions Introduction Chapter 9 Graph Algorithms graph theory useful in practice represent many real-life problems can be slow if not careful with data structures 2 Definitions an undirected graph G = (V, E) is

More information

Chapter 9 Graph Algorithms

Chapter 9 Graph Algorithms Chapter 9 Graph Algorithms 2 Introduction graph theory useful in practice represent many real-life problems can be slow if not careful with data structures 3 Definitions an undirected graph G = (V, E)

More information

國立清華大學電機工程學系. Outline

國立清華大學電機工程學系. Outline 國立清華大學電機工程學系 EE Data Structure Chapter Graph (Part I) Outline The Graph Abstract Data Type Introduction Definitions Graph Representations Elementary Graph Operations Minimum Cost Spanning Trees ch.- River

More information

Abstract Data Types. CptS 223 Advanced Data Structures. Larry Holder School of Electrical Engineering and Computer Science Washington State University

Abstract Data Types. CptS 223 Advanced Data Structures. Larry Holder School of Electrical Engineering and Computer Science Washington State University Abstract Data Types CptS 223 Advanced Data Structures Larry Holder School of Electrical Engineering and Computer Science Washington State University 1 Purpose Abstract Data Types (ADTs) Lists Stacks Queues

More information

FORM 2 (Please put your name and form # on the scantron!!!!)

FORM 2 (Please put your name and form # on the scantron!!!!) CS 161 Exam 2: FORM 2 (Please put your name and form # on the scantron!!!!) True (A)/False(B) (2 pts each): 1. Recursive algorithms tend to be less efficient than iterative algorithms. 2. A recursive function

More information

Data Structures and Algorithms

Data Structures and Algorithms Data Structures and Algorithms First Semester 2017/2018 Linked Lists Eng. Anis Nazer Linked List ADT Is a list of nodes Each node has: data (can be any thing, int, char, Person, Point, day,...) link to

More information

UNIT IV -NON-LINEAR DATA STRUCTURES 4.1 Trees TREE: A tree is a finite set of one or more nodes such that there is a specially designated node called the Root, and zero or more non empty sub trees T1,

More information

CSCE 110 PROGRAMMING FUNDAMENTALS

CSCE 110 PROGRAMMING FUNDAMENTALS CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 16. Linked Lists Prof. amr Goneid, AUC 1 Linked Lists Prof. amr Goneid, AUC 2 Linked Lists The Linked List Structure Some Linked List

More information

CSE 100 Practice Final Exam

CSE 100 Practice Final Exam CSE 100 Practice Final Exam Please note that this practice final only serves as a template and does not exhaustively cover all the topics that are on the actual final. The final exam will cover all the

More information

Figure 1. A breadth-first traversal.

Figure 1. A breadth-first traversal. 4.3 Tree Traversals Stepping, or iterating, through the entries of a linearly ordered list has only two obvious orders: from front to back or from back to front. There is no obvious traversal of a general

More information

Test 1: CPS 100. Owen Astrachan. October 11, 2000

Test 1: CPS 100. Owen Astrachan. October 11, 2000 Test 1: CPS 100 Owen Astrachan October 11, 2000 Name: Login: Honor code acknowledgment (signature) Problem 1 Problem 2 Problem 3 Problem 4 TOTAL: value 30 pts. 16 pts. 12 pts. 20 pts. 78 pts. grade This

More information

Graphs. The ultimate data structure. graphs 1

Graphs. The ultimate data structure. graphs 1 Graphs The ultimate data structure graphs 1 Definition of graph Non-linear data structure consisting of nodes & links between them (like trees in this sense) Unlike trees, graph nodes may be completely

More information

The University of Nottingham

The University of Nottingham The University of Nottingham SCHOOL OF COMPUTER SCIENCE A LEVEL 2 MODULE, SPRING SEMESTER 2011-2012 G52CPP C++ Programming Examination Time allowed TWO hours Candidates may complete the front cover of

More information

Graph Traversals BFS & DFS 1 CS S-16

Graph Traversals BFS & DFS 1 CS S-16 CS-8S- BFS & DFS -: Visit every vertex, in an order defined by the topololgy of the graph. Two major traversals: Depth First Search Breadth First Search -: Depth First Search Starting from a specific node

More information

18: GRAPH DATA STRUCTURES. Introduction

18: GRAPH DATA STRUCTURES. Introduction 18: GRAPH DATA STRUCTURES Introduction... 1 Describing graphs... Directed Graphs... 3 Traversing a graph... EXERCISE: Traversal... 8 Implementing a Graph... 9 EXERCISE: Looking at a Graph... 1 EXERICISE:

More information

Abstract Data Types 1

Abstract Data Types 1 Abstract Data Types 1 Purpose Abstract Data Types (ADTs) Lists Stacks Queues 2 Primitive vs. Abstract Data Types Primitive DT: programmer ADT: programmer Interface (API) data Implementation (methods) Data

More information

1. Stack overflow & underflow 2. Implementation: partially filled array & linked list 3. Applications: reverse string, backtracking

1. Stack overflow & underflow 2. Implementation: partially filled array & linked list 3. Applications: reverse string, backtracking Review for Test 2 (Chapter 6-10) Chapter 6: Template functions & classes 1) What is the primary purpose of template functions? A. To allow a single function to be used with varying types of arguments B.

More information

LECTURE 11 TREE TRAVERSALS

LECTURE 11 TREE TRAVERSALS DATA STRUCTURES AND ALGORITHMS LECTURE 11 TREE TRAVERSALS IMRAN IHSAN ASSISTANT PROFESSOR AIR UNIVERSITY, ISLAMABAD BACKGROUND All the objects stored in an array or linked list can be accessed sequentially

More information

B-Trees. nodes with many children a type node a class for B-trees. an elaborate example the insertion algorithm removing elements

B-Trees. nodes with many children a type node a class for B-trees. an elaborate example the insertion algorithm removing elements B-Trees 1 B-Trees nodes with many children a type node a class for B-trees 2 manipulating a B-tree an elaborate example the insertion algorithm removing elements MCS 360 Lecture 35 Introduction to Data

More information

Algorithm and Data Structures, Supplemental Solution 2010

Algorithm and Data Structures, Supplemental Solution 2010 Algorithm and Data Structures, Supplemental Solution 00 Question ( marks) (a) marks class Stack { public: void push(int x); int pop(void); bool isempty(); Stack() { top = NULL; void display(); ; private:

More information

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol. 1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol. B. Outputs to the console a floating point number f1 in scientific format

More information

CS4800: Algorithms & Data Jonathan Ullman

CS4800: Algorithms & Data Jonathan Ullman CS4800: Algorithms & Data Jonathan Ullman Lecture 11: Graphs Graph Traversals: BFS Feb 16, 2018 What s Next What s Next Graph Algorithms: Graphs: Key Definitions, Properties, Representations Exploring

More information

Graphs. The ultimate data structure. graphs 1

Graphs. The ultimate data structure. graphs 1 Graphs The ultimate data structure graphs 1 Definition of graph Non-linear data structure consisting of nodes & links between them (like trees in this sense) Unlike trees, graph nodes may be completely

More information

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive) Final Exam Exercises Chapters 1-7 + 11 Write C++ code to: l Determine if a number is odd or even CS 2308 Fall 2016 Jill Seaman l Determine if a number/character is in a range - 1 to 10 (inclusive) - between

More information

University of Waterloo Department of Electrical and Computer Engineering ECE 250 Data Structures and Algorithms. Final Examination

University of Waterloo Department of Electrical and Computer Engineering ECE 250 Data Structures and Algorithms. Final Examination University of Waterloo Department of Electrical and Computer Engineering ECE 250 Data Structures and Algorithms Instructor: Douglas Wilhelm Harder Time: 2.5 hours Aides: none 14 pages Final Examination

More information

problem statement Prim s algorithm a multiple key map representation for a tree code for Prim s algorithm

problem statement Prim s algorithm a multiple key map representation for a tree code for Prim s algorithm Greedy Algorithms 1 Shortest Paths from a Vertex Dijkstra s algorithm code for Dijkstra s algorithm cost analysis 2 Minimum Spanning Tree Prim s algorithm a multiple key map representation for a tree code

More information

selectors, methodsinsert() andto_string() the depth of a tree and a membership function

selectors, methodsinsert() andto_string() the depth of a tree and a membership function Binary Search Trees 1 Sorting Numbers using a Tree a sorting algorithm using a tree of integer numbers 2 Header Files defining a node struct defining a tree class 3 Definition of Methods selectors, methodsinsert()

More information

Queue Implementations

Queue Implementations Queue Implementations 1 Circular Queues buffer of fixed capacity improvements and cost estimates 2 Deques the double ended queue queue as double linked circular list MCS 360 Lecture 17 Introduction to

More information

Data Structures and Algorithms for Engineers

Data Structures and Algorithms for Engineers 4-63 Data Structures and Algorithms for Engineers David Vernon Carnegie Mellon University Africa vernon@cmuedu wwwvernoneu Data Structures and Algorithms for Engineers 1 Carnegie Mellon University Africa

More information

CSE 100 Minimum Spanning Trees Prim s and Kruskal

CSE 100 Minimum Spanning Trees Prim s and Kruskal CSE 100 Minimum Spanning Trees Prim s and Kruskal Your Turn The array of vertices, which include dist, prev, and done fields (initialize dist to INFINITY and done to false ): V0: dist= prev= done= adj:

More information

Motivation. Using Iterators to Create Generic Code

Motivation. Using Iterators to Create Generic Code CS 310 Iterators, Page 1 Motivation A C++ pointer uses the deference operator * to access the data it points to. the arrow operator -> is a combination of * and. In an array, we use the pre/post increment

More information

1) What is the primary purpose of template functions? 2) Suppose bag is a template class, what is the syntax for declaring a bag b of integers?

1) What is the primary purpose of template functions? 2) Suppose bag is a template class, what is the syntax for declaring a bag b of integers? Review for Final (Chapter 6 13, 15) 6. Template functions & classes 1) What is the primary purpose of template functions? A. To allow a single function to be used with varying types of arguments B. To

More information

Structured Data. CIS 15 : Spring 2007

Structured Data. CIS 15 : Spring 2007 Structured Data CIS 15 : Spring 2007 Functionalia HW4 Part A due this SUNDAY April 1st: 11:59pm Reminder: I do NOT accept LATE HOMEWORK. Today: Dynamic Memory Allocation Allocating Arrays Returning Pointers

More information

C++ Final Exam 2017/2018

C++ Final Exam 2017/2018 1) All of the following are examples of integral data types EXCEPT. o A Double o B Char o C Short o D Int 2) After the execution of the following code, what will be the value of numb if the input value

More information

undirected graph 5 vertices 7 edges directed graph 6 vertices 8 edges

undirected graph 5 vertices 7 edges directed graph 6 vertices 8 edges ! "# $ % ' ( ) * * ## A A B B F E D C undirected graph 5 vertices 7 edges C D directed graph 6 vertices 8 edges E 1 , $ % # ' $ % ( $ %! * -* $ %. * #$/$' $' 0$ ( 0$! $ )*,1/$ * 2 3 "4!*!" 4 * # * 2 )

More information

FORM 1 (Please put your name and form # on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

FORM 1 (Please put your name and form # on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each): FORM 1 (Please put your name and form # on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each): 1. When you attach & after the datatype in the parameter list of a function, the variable following

More information

double d0, d1, d2, d3; double * dp = new double[4]; double da[4];

double d0, d1, d2, d3; double * dp = new double[4]; double da[4]; All multiple choice questions are equally weighted. You can generally assume that code shown in the questions is intended to be syntactically correct, unless something in the question or one of the answers

More information

University of Waterloo Department of Electrical and Computer Engineering ECE 250 Data Structures and Algorithms. Final Examination

University of Waterloo Department of Electrical and Computer Engineering ECE 250 Data Structures and Algorithms. Final Examination ECE 25 Data Structures and Algorithms University of Waterloo Department of Electrical and Computer Engineering ECE 25 Data Structures and Algorithms Instructor: Douglas Wilhelm Harder Time: 2.5 hours Aides:

More information

CSC 8301 Design & Analysis of Algorithms: Warshall s, Floyd s, and Prim s algorithms

CSC 8301 Design & Analysis of Algorithms: Warshall s, Floyd s, and Prim s algorithms CSC 8301 Design & Analysis of Algorithms: Warshall s, Floyd s, and Prim s algorithms Professor Henry Carter Fall 2016 Recap Space-time tradeoffs allow for faster algorithms at the cost of space complexity

More information

LAB 5, THE HIDDEN DELIGHTS OF LINKED LISTS

LAB 5, THE HIDDEN DELIGHTS OF LINKED LISTS LAB 5, THE HIDDEN DELIGHTS OF LINKED LISTS Questions are based on the Main and Savitch review questions for chapter 5 in the Exam Preparation section of the webct course page. In case you haven t observed

More information

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct.

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct. MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct. In linked list the elements are necessarily to be contiguous In linked list the elements may locate at far positions

More information

Array Elements as Function Parameters

Array Elements as Function Parameters Arrays Class 26 Array Elements as Function Parameters we have seen that array elements are simple variables they can be used anywhere a normal variable can unsigned values [] {10, 15, 20}; unsigned quotient;

More information

Homework Assignment #3 Graph

Homework Assignment #3 Graph CISC 4080 Computer Algorithms Spring, 2019 Homework Assignment #3 Graph Some of the problems are adapted from problems in the book Introduction to Algorithms by Cormen, Leiserson and Rivest, and some are

More information

CS/COE 1501 cs.pitt.edu/~bill/1501/ Graphs

CS/COE 1501 cs.pitt.edu/~bill/1501/ Graphs CS/COE 1501 cs.pitt.edu/~bill/1501/ Graphs 5 3 2 4 1 0 2 Graphs A graph G = (V, E) Where V is a set of vertices E is a set of edges connecting vertex pairs Example: V = {0, 1, 2, 3, 4, 5} E = {(0, 1),

More information

Practice Problems for the Final

Practice Problems for the Final ECE-250 Algorithms and Data Structures (Winter 2012) Practice Problems for the Final Disclaimer: Please do keep in mind that this problem set does not reflect the exact topics or the fractions of each

More information

CSCI-1200 Computer Science II Spring 2006 Test 3 Practice Problem Solutions

CSCI-1200 Computer Science II Spring 2006 Test 3 Practice Problem Solutions CSCI-1200 Computer Science II Spring 2006 Test 3 Practice Problem Solutions 1. You are given a map that associates strings with lists of strings. The definition is: map words; Write

More information

Data Structures And Algorithms

Data Structures And Algorithms Data Structures And Algorithms Binary Trees Eng. Anis Nazer First Semester 2017-2018 Definitions Linked lists, arrays, queues, stacks are linear structures not suitable to represent hierarchical data,

More information

Data Structures and Algorithms

Data Structures and Algorithms Data Structures and Algorithms CS5-5S-6 Graph Traversals BFS & DFS David Galles Department of Computer Science University of San Francisco 6-: Graph Traversals Visit every vertex, in an order defined by

More information

UNIT Name the different ways of representing a graph? a.adjacencymatrix b. Adjacency list

UNIT Name the different ways of representing a graph? a.adjacencymatrix b. Adjacency list UNIT-4 Graph: Terminology, Representation, Traversals Applications - spanning trees, shortest path and Transitive closure, Topological sort. Sets: Representation - Operations on sets Applications. 1. Name

More information

Lists. linking nodes. constructors. chasing pointers. MCS 360 Lecture 11 Introduction to Data Structures Jan Verschelde, 17 September 2010.

Lists. linking nodes. constructors. chasing pointers. MCS 360 Lecture 11 Introduction to Data Structures Jan Verschelde, 17 September 2010. 1 2 3 MCS 360 Lecture 11 Introduction to Data Structures Jan Verschelde, 17 September 2010 1 2 3 efficient updates with lists At http://www.sgi.com/tech/stl/ is the Standard Template Library Programmer

More information

CS 2604 Homework 1 Greatest Hits of C++ Summer 2000

CS 2604 Homework 1 Greatest Hits of C++ Summer 2000 Instructions: This homework assignment covers some of the basic C++ background you should have in order to take this course. I. Pointers Opscan forms will be passed out in class and will be available at

More information

Faculty of Information and Communication Technologies

Faculty of Information and Communication Technologies Swinburne University Of Technology Faculty of Information and Communication Technologies ASSIGNMENT COVER SHEET Subject Code: Subject Title: Assignment number and title: Due date: Lecturer: HIT3303 Data

More information

Question Paper Code : 97044

Question Paper Code : 97044 Reg. No. : Question Paper Code : 97044 B.E./B.Tech. DEGREE EXAMINATION NOVEMBER/DECEMBER 2014 Third Semester Computer Science and Engineering CS 6301 PROGRAMMING AND DATA STRUCTURES-II (Regulation 2013)

More information

( ) n 3. n 2 ( ) D. Ο

( ) n 3. n 2 ( ) D. Ο CSE 0 Name Test Summer 0 Last Digits of Mav ID # Multiple Choice. Write your answer to the LEFT of each problem. points each. The time to multiply two n n matrices is: A. Θ( n) B. Θ( max( m,n, p) ) C.

More information

SOLUTIONS TO EXERCISES PART ONE: Problem-Solving Techniques

SOLUTIONS TO EXERCISES PART ONE: Problem-Solving Techniques SOLUTIONS TO EXERCISES PART ONE: Problem-Solving Techniques 1 Principles of Programming and Software Engineering 1 const CENTS_PER_DOLLAR = 100; void computechange(int dollarcost, int centscost, int& d,

More information

Introduction p. 1 Pseudocode p. 2 Algorithm Header p. 2 Purpose, Conditions, and Return p. 3 Statement Numbers p. 4 Variables p. 4 Algorithm Analysis

Introduction p. 1 Pseudocode p. 2 Algorithm Header p. 2 Purpose, Conditions, and Return p. 3 Statement Numbers p. 4 Variables p. 4 Algorithm Analysis Introduction p. 1 Pseudocode p. 2 Algorithm Header p. 2 Purpose, Conditions, and Return p. 3 Statement Numbers p. 4 Variables p. 4 Algorithm Analysis p. 5 Statement Constructs p. 5 Pseudocode Example p.

More information

Mystery Algorithm! ALGORITHM MYSTERY( G = (V,E), start_v ) mark all vertices in V as unvisited mystery( start_v )

Mystery Algorithm! ALGORITHM MYSTERY( G = (V,E), start_v ) mark all vertices in V as unvisited mystery( start_v ) Mystery Algorithm! 0 2 ALGORITHM MYSTERY( G = (V,E), start_v ) mark all vertices in V as unvisited mystery( start_v ) 3 1 4 7 6 5 mystery( v ) mark vertex v as visited PRINT v for each vertex w adjacent

More information

cameron grace derek cameron

cameron grace derek cameron Test 1: CPS 100E Owen Astrachan and Dee Ramm November 19, 1996 Name: Honor code acknowledgement (signature) Problem 1 Problem 2 Problem 3 Problem 4 Problem 5 Extra TOTAL: value 15 pts. 15 pts. 8 pts. 12

More information

CS 2604 Homework 2 Solution for Greatest Hits of C++ Fall 2000

CS 2604 Homework 2 Solution for Greatest Hits of C++ Fall 2000 Instructions: This homework assignment covers some of the basic C++ background you should have in order to take this course. I. Pointers Opscan forms will be passed out in class. Write your name and code

More information

Introduction: (Edge-)Weighted Graph

Introduction: (Edge-)Weighted Graph Introduction: (Edge-)Weighted Graph c 8 7 a b 7 i d 9 e 8 h 6 f 0 g These are computers and costs of direct connections. What is a cheapest way to network them? / 8 (Edge-)Weighted Graph Many useful graphs

More information

Chapter 9. Priority Queue

Chapter 9. Priority Queue Chapter 9 Priority Queues, Heaps, Graphs Spring 2015 1 Priority Queue Priority Queue An ADT in which only the item with the highest priority can be accessed 2Spring 2015 Priority Depends on the Application

More information

! Determine if a number is odd or even. ! Determine if a number/character is in a range. - 1 to 10 (inclusive) - between a and z (inclusive)

! Determine if a number is odd or even. ! Determine if a number/character is in a range. - 1 to 10 (inclusive) - between a and z (inclusive) Final Exam Exercises CS 2308 Spring 2014 Jill Seaman Chapters 1-7 + 11 Write C++ code to: Determine if a number is odd or even Determine if a number/character is in a range - 1 to 10 (inclusive) - between

More information

Lecture 23 Representing Graphs

Lecture 23 Representing Graphs Lecture 23 Representing Graphs 15-122: Principles of Imperative Computation (Fall 2018) Frank Pfenning, André Platzer, Rob Simmons, Penny Anderson, Iliano Cervesato In this lecture we introduce graphs.

More information

CSE030 Fall 2012 Final Exam Friday, December 14, PM

CSE030 Fall 2012 Final Exam Friday, December 14, PM CSE030 Fall 2012 Final Exam Friday, December 14, 2012 3-6PM Write your name here and at the top of each page! Name: Select your lab session: Tuesdays Thursdays Paper. If you have any questions or need

More information