Lab5 - << endl<<"\t" for(i=0 i<n i...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
CS 284 Algorithms Summer semester 2010 Lab 7 Lab objectives: - Understand and implement the graph searching algorithms. Related chapter(s): 22. Lab instructions (steps): 1. Write the following program and run it. #include <iostream> #include <ctime> #include <queue> const int n = 8; int A[n][n]; int color[n], d[n], f[n], p[n], t; void reset(); void printAdjacency(); void printTree( bool bfs); void bfs( int s); void dfs( int s); using namespace std; void main() { srand ( 1 ); int s; for ( int i=0; i<n-1; ++i){ for ( int j=i+1; j<n; ++j){ if (rand()%100<=33) A[i][j]=A[j][i]=1; else A[i][j]=A[j][i]=0; } } printAdjacency(); reset(); s=7; cout << "\nStarting node is " << s+1 << endl; bfs(s); printTree( true ); reset(); dfs(s); printTree( false ); } void reset(){ t=0; for ( int i=0; i<n; i++){ color[i]=1; // colors: 1 for white, 2 for grey, 3 for black d[i]= f[i]=100; // in BFS: d is distance from s to u (100 for infinity), // in DFS: d and f are discovery time and finish time p[i]=-1; // predecessor or parent of u (-1 for NIL) } } void printAdjacency(){ int i,j; cout << " Adjacency Matrix : "
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: << endl << "\t" ; for (i=0; i<n; ++i) cout << "\t" << i+1 ; cout << endl; cout << endl; for (i=0; i<n; ++i){ cout << i+1 << "\t\t" ; for (j=0; j<n; ++j) cout << A[i][j] << "\t" ; cout << endl; } } void bfs( int s){ // Your code here } void dfs( int s){ // Your code here } void printTree( bool bfs) { if (bfs) cout << "\nBFS Tree : " << endl; else cout << "\nDFS Tree : " << endl; for ( int i=0; i<n; ++i) cout << "p[" << i+1 << "] " << " is " << p[i]+1 << endl; } 2. Implement the functions bfs and dfs as explained in the slides (consider adjacent nodes in increasing order of their IDs; i.e., if node 4 has nodes 1 and 7 as its adjacent nodes, then you should consider node 1 before node 7). 3. Get the output. 4. Is the graph connected? Justify your answer. Tasks: 1. Output obtained from step 3. 2. The functions implemented at step 2 3. Answer to the question in step 4....
View Full Document

{[ snackBarMessage ]}

Page1 / 2

Lab5 - << endl<<"\t" for(i=0 i<n i...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online