19 Thdec ACA
19 Thdec ACA
• O(2n − 1): Each recursive call splits into two smaller recursive calls, doubling the work with each additional disk.
Space Complexity:
• O(n): Due to the recursive call stack.
Code:
# include < iostream >
using namespace std ;
int main ()
{
int n ;
cout << " Enter the number of disks : " ;
cin >> n ;
if ( n <= 0)
{
cout << " Number of disks must be positive . " << endl ;
return 0;
}
cout << " The sequence of moves to solve Tower of Hanoi is :\ n " ;
towerOfHanoi (n , ’A ’ , ’C ’ , ’B ’) ;
return 0;
}
Output 1:
Enter the number of disks: 2
The sequence of moves to solve Tower of Hanoi is:
Move disk 1 from A to B
Move disk 2 from A to C
Move disk 1 from B to C
49
Output 2:
Enter the number of disks: 3
The sequence of moves to solve Tower of Hanoi is:
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C
int main () {
int n ;
cout << " Enter the number of elements : " ;
cin >> n ;
if ( n <= 0)
{
cout << " Number of elements must be positive . " << endl ;
return 0;
}
50
Output 1:
Enter the number of elements: 5
Enter the elements: 1 2 3 4 5
Sum of array elements: 15
Output 2:
Enter the number of elements: 4
Enter the elements: 10 20 30 40
Sum of array elements: 100
9 Graphs
9.1 Depth First Traversal
Algorithm:
1. Use a recursive function to perform Depth First Search (DFS).
2. Define a function DFS(node, visited, graph):
• Base Case: If the node has already been visited, return.
• Recursive Case:
(a) Mark the current node as visited.
(b) Print the current node or store it in a result list.
(c) Recursively call DFS for all unvisited neighbors of the current node.
3. For disconnected graphs:
• Iterate through all nodes and perform DFS for each unvisited node.
Time Complexity:
• O(V + E): V is the number of vertices, and E is the number of edges. Each vertex and edge is visited once.
Space Complexity:
• O(V ): Due to the recursion stack and visited array.
Code:
# include < iostream >
# include < vector >
# include < list >
using namespace std ;
void DFS ( int node , vector < bool > & visited , const vector < list < int > > & graph )
{
visited [ node ] = true ;
cout << node << " " ;
int main ()
{
int V , E ;
cout << " Enter the number of vertices : " ;
cin >> V ;
cout << " Enter the number of edges : " ;
cin >> E ;
51
{
int u , v ;
cin >> u >> v ;
graph [ u ]. push_back ( v ) ;
graph [ v ]. push_back ( u ) ;
}
cout << " Depth First Traversal starting from node 0: " ;
for ( int i = 0; i < V ; i ++)
if (! visited [ i ])
DFS (i , visited , graph ) ;
cout << endl ;
return 0;
}
Output 1:
Enter the number of vertices: 5
Enter the number of edges: 4
Enter the edges (u v):
0 1
0 2
1 3
1 4
Depth First Traversal starting from node 0: 0 1 3 4 2
Output 2:
Enter the number of vertices: 6
Enter the number of edges: 5
Enter the edges (u v):
0 1
0 2
1 3
3 4
4 5
Depth First Traversal starting from node 0: 0 1 3 4 5 2
52