codeparrot/xlcost-text-to-code huggingface dataset:
Check if two given strings are isomorphic to each other | C ++ program for the above approach ; This function returns true if str1 and str2 are isomorphic ; Length of both strings must be same for one to one correspondence ; For counting the previous appearances of character in both the strings ; Process all characters one by one ; For string to be isomorphic the previous counts of appearances of current character in both string must be same if it is not same we return false . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX_CHARS  26 NEW_LINE bool areIsomorphic ( string str1 , string str2 ) { int n = str1 . length ( ) , m = str2 . length ( ) ; if ( n != m ) return false ; int count [ MAX_CHARS ] = { 0 } ; int dcount [ MAX_CHARS ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { count [ str1 [ i ] - ' a ' ] ++ ; dcount [ str2 [ i ] - ' a ' ] ++ ; if ( count [ str1 [ i ] - ' a ' ] != dcount [ str2 [ i ] - ' a ' ] ) return false ; } return true ; } int main ( ) { cout << areIsomorphic ( " aab " , " xxy " ) << endl ; cout << areIsomorphic ( " aab " , " xyz " ) << endl ; return 0 ; }
Minimum insertions to form shortest palindrome | C ++ program to find minimum number of insertions on left side to form a palindrome . ; Returns true if a string str [ st . . end ] is palindrome ; Returns count of insertions on left side to make str [ ] a palindrome ; Find the largest prefix of given string that is palindrome . ; Characters after the palindromic prefix must be added at the beginning also to make the complete string palindrome ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPalin ( char str [ ] , int st , int end ) { while ( st < end ) { if ( str [ st ] != str [ end ] ) return false ; st ++ ; end -- ; } return true ; } int findMinInsert ( char str [ ] , int n ) { for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( isPalin ( str , 0 , i ) ) return ( n - i - 1 ) ; } } int main ( ) { char Input [ ] = " JAVA " ; printf ( " % d " , findMinInsert ( Input , strlen ( Input ) ) ) ; return 0 ; }
Remove repeated digits in a given number | C ++ program to remove repeated digits ; Store first digits as previous digit ; Initialize power ; Iterate through all digits of n , note that the digits are processed from least significant digit to most significant digit . ; Store current digit ; Add the current digit to the beginning of result ; Update previous result and power ; Remove last digit from n ; Driver program
#include <iostream> NEW_LINE using namespace std ; long int removeRecur ( long int n ) { int prev_digit = n % 10 ; long int pow = 10 ; long int res = prev_digit ; while ( n ) { int curr_digit = n % 10 ; if ( curr_digit != prev_digit ) { res += curr_digit * pow ; prev_digit = curr_digit ; pow *= 10 ; } n = n / 10 ; } return res ; } int main ( ) { long int n = 12224 ; cout << removeRecur ( n ) ; return 0 ; }
Remove " b " and " ac " from a given string | A C ++ program to remove " b " and ' ac ' from input string ; The main function that removes occurrences of " a " and " bc " in input string ; previous character ; current character ; check if current and next character forms ac ; if current character is b ; if current char is ' c ▁ & & ▁ last ▁ char ▁ in ▁ output ▁ ▁ is ▁ ' a ' so delete both  ; else copy curr char to output string ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void stringFilter ( char * str ) { int n = strlen ( str ) ; int i = -1 ; int j = 0 ; while ( j < n ) { if ( j < n - 1 && str [ j ] == ' a ' && str [ j + 1 ] == ' c ' ) j += 2 ; else if ( str [ j ] == ' b ' ) j ++ ; else if ( i >= 0 && str [ j ] == ' c ' && str [ i ] == ' a ' ) i -- , j ++ ; else str [ ++ i ] = str [ j ++ ] ; } str [ ++ i ] = ' \0' ; } int main ( ) { char str1 [ ] = " ad " ; cout << " Input ▁ = > ▁ " << str1 << " Output = > " stringFilter ( str1 ) ; cout << str1 << endl << endl ; char str2 [ ] = " acbac " ; cout << " Input ▁ = > ▁ " << str2 << " Output = > " stringFilter ( str2 ) ; cout << str2 << endl << endl ; char str3 [ ] = " aaac " ; cout << " Input ▁ = > ▁ " << str3 << " Output = > " stringFilter ( str3 ) ; cout << str3 << endl << endl ; char str4 [ ] = " react " ; cout << " Input ▁ = > ▁ " << str4 << " Output = > " stringFilter ( str4 ) ; cout << str4 << endl << endl ; char str5 [ ] = " aa " ; cout << " Input ▁ = > ▁ " << str5 << " Output = > " stringFilter ( str5 ) ; cout << str5 << endl << endl ; char str6 [ ] = " ababaac " ; cout << " Input ▁ = > ▁ " << str6 << " Output = > " stringFilter ( str6 ) ; cout << str6 << endl << endl ; char str [ ] = " abc " ; cout << " Input ▁ = > ▁ " << str << " Output = > " stringFilter ( str ) ; cout << str << endl << endl ; return 0 ; }
Write your own atoi ( ) | A simple C ++ program for implementation of atoi ; if whitespaces then ignore . ; sign of number ; checking for valid input ; handling overflow test case ; Driver Code ; Functional Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int myAtoi ( const char * str ) { int sign = 1 , base = 0 , i = 0 ; while ( str [ i ] == ' ▁ ' ) { i ++ ; } if ( str [ i ] == ' - ' str [ i ] == ' + ' ) { sign = 1 - 2 * ( str [ i ++ ] == ' - ' ) ; } while ( str [ i ] >= '0' && str [ i ] <= '9' ) { if ( base > INT_MAX / 10 || ( base == INT_MAX / 10 && str [ i ] - '0' > 7 ) ) { if ( sign == 1 ) return INT_MAX ; else return INT_MIN ; } base = 10 * base + ( str [ i ++ ] - '0' ) ; } return base * sign ; } int main ( ) { char str [ ] = " ▁ - 123" ; int val = myAtoi ( str ) ; cout << " ▁ " << val ; return 0 ; }
Check whether two strings are anagram of each other | C ++ program to check if two strings are anagrams of each other ; function to check if two strings are anagrams of each other ; Create a count array and initialize all values as 0 ; For each character in input strings , increment count in the corresponding count array ; If both strings are of different length . Removing this condition will make the program fail for strings like " aaca " and " aca " ; See if there is any non - zero value in count array ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define NO_OF_CHARS  256 NEW_LINE bool areAnagram ( char * str1 , char * str2 ) { int count [ NO_OF_CHARS ] = { 0 } ; int i ; for ( i = 0 ; str1 [ i ] && str2 [ i ] ; i ++ ) { count [ str1 [ i ] ] ++ ; count [ str2 [ i ] ] -- ; } if ( str1 [ i ] str2 [ i ] ) return false ; for ( i = 0 ; i < NO_OF_CHARS ; i ++ ) if ( count [ i ] ) return false ; return true ; } int main ( ) { char str1 [ ] = " geeksforgeeks " ; char str2 [ ] = " forgeeksgeeks " ; if ( areAnagram ( str1 , str2 ) ) cout << " The ▁ two ▁ strings ▁ are ▁ anagram ▁ of ▁ each ▁ other " ; else cout << " The ▁ two ▁ strings ▁ are ▁ not ▁ anagram ▁ of ▁ each ▁ " " other " ; return 0 ; }
Length of the longest substring without repeating characters | C ++ program to find the length of the longest substring without repeating characters ; This functionr eturns true if all characters in str [ i . . j ] are distinct , otherwise returns false ; Note : Default values in visited are false ; Returns length of the longest substring with all distinct characters . ; result ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool areDistinct ( string str , int i , int j ) { vector < bool > visited ( 26 ) ; for ( int k = i ; k <= j ; k ++ ) { if ( visited [ str [ k ] - ' a ' ] == true ) return false ; visited [ str [ k ] - ' a ' ] = true ; } return true ; } int longestUniqueSubsttr ( string str ) { int n = str . size ( ) ; int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = i ; j < n ; j ++ ) if ( areDistinct ( str , i , j ) ) res = max ( res , j - i + 1 ) ; return res ; } int main ( ) { string str = " geeksforgeeks " ; cout << " The ▁ input ▁ string ▁ is ▁ " << str << endl ; int len = longestUniqueSubsttr ( str ) ; cout << " The ▁ length ▁ of ▁ the ▁ longest ▁ non - repeating ▁ " " character ▁ substring ▁ is ▁ " << len ; return 0 ; }
Given a string , find its first non | CPP program to find first non - repeating character ; this function return the index of first non - repeating character if found , or else it returns - 1 ; initializing all elements to - 1 ; sets all repeating characters to - 2 and non - repeating characters contain the index where they occur ; If this character is not - 1 or - 2 then it means that this character occurred only once so find the min index of all characters that occur only once , that 's our first index ; if res remains INT_MAX , it means there are no characters that repeat only once or the string is empty
# include <iostream> NEW_LINE # include <climits> NEW_LINE using namespace std ; int firstNonRepeating ( string str ) { int fi [ 256 ] ; for ( int i = 0 ; i < 256 ; i ++ ) fi [ i ] = -1 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( fi [ str [ i ] ] == -1 ) { fi [ str [ i ] ] = i ; } else { fi [ str [ i ] ] = -2 ; } } int res = INT_MAX ; for ( int i = 0 ; i < 256 ; i ++ ) { if ( fi [ i ] >= 0 ) res = min ( res , fi [ i ] ) ; } if ( res == INT_MAX ) return -1 ; else return res ; } int main ( ) { string str ; str = " geeksforgeeks " ; int firstIndex = firstNonRepeating ( str ) ; if ( firstIndex == -1 ) cout << " Either ▁ all ▁ characters ▁ are ▁ repeating ▁ or ▁ string ▁ is ▁ empty " ; else cout << " First ▁ non - repeating ▁ character ▁ is ▁ " << str [ firstIndex ] ; return 0 ; }
Remove duplicates from a given string | C ++ program to create a unique string ; Function to make the string unique ; loop to traverse the string and check for repeating chars using IndexOf ( ) method in Java ; character at i 'th index of s ; If c is present in str , it returns the index of c , else it returns npos ; Adding c to str if npos is returned ; Driver code ; Input string with repeating chars
#include <bits/stdc++.h> NEW_LINE using namespace std ; string unique ( string s ) { string str ; int len = s . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) { char c = s [ i ] ; auto found = str . find ( c ) ; if ( found == std :: string :: npos ) { str += c ; } } return str ; } int main ( ) { string s = " geeksforgeeks " ; cout << unique ( s ) << endl ; }
Sum of all subsets whose sum is a Perfect Number from a given array | C ++ program for the above approach ; Function to check is a given number is a perfect number or not ; Stores the sum of its divisors ; Add all divisors of x to sum_div ; If the sum of divisors is equal to the given number , return true ; Otherwise , return false ; Function to find sum of all subsets from an array whose sum is a perfect number ; Print the current subset sum if it is a perfect number ; Check if sum is a perfect number or not ; Calculate sum of the subset including arr [ l ] ; Calculate sum of the subset excluding arr [ l ] ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int isPerfect ( int x ) { int sum_div = 1 ; for ( int i = 2 ; i <= x / 2 ; ++ i ) { if ( x % i == 0 ) { sum_div += i ; } } if ( sum_div == x ) { return 1 ; } else return 0 ; } void subsetSum ( int arr [ ] , int l , int r , int sum = 0 ) { if ( l > r ) { if ( isPerfect ( sum ) ) { cout << sum << " ▁ " ; } return ; } subsetSum ( arr , l + 1 , r , sum + arr [ l ] ) ; subsetSum ( arr , l + 1 , r , sum ) ; } int main ( ) { int arr [ ] = { 5 , 4 , 6 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; subsetSum ( arr , 0 , N - 1 ) ; return 0 ; }
Print all possible ways to split an array into K subsets | C ++ program for the above approach ; Utility function to find all possible ways to split array into K subsets ; If count of elements in K subsets are greater than or equal to N ; If count of subsets formed is equal to K ; Print K subsets by splitting array into K subsets ; Print current subset ; If current element is the last element of the subset ; Otherwise ; If any subset is occupied , then push the element in that first ; Recursively do the same for remaining elements ; Backtrack ; Otherwise , push it in an empty subset and increase the subset count by 1 ; Break to avoid the case of going in other empty subsets , if available , and forming the same combination ; Function to to find all possible ways to split array into K subsets ; Stores K subset by splitting array into K subsets ; Size of each subset must be less than the number of elements ; Driver Code ; Given array ; Given K ; Size of the array ; Prints all possible splits into subsets
#include <bits/stdc++.h> NEW_LINE using namespace std ; void PartitionSub ( int arr [ ] , int i , int N , int K , int nos , vector < vector < int > > & v ) { if ( i >= N ) { if ( nos == K ) { for ( int x = 0 ; x < v . size ( ) ; x ++ ) { cout << " { ▁ " ; for ( int y = 0 ; y < v [ x ] . size ( ) ; y ++ ) { cout << v [ x ] [ y ] ; if ( y == v [ x ] . size ( ) - 1 ) { cout << " ▁ " ; } else { cout << " , ▁ " ; } } if ( x == v . size ( ) - 1 ) { cout << " } " ; } else { cout << " } , ▁ " ; } } cout << endl ; } return ; } for ( int j = 0 ; j < K ; j ++ ) { if ( v [ j ] . size ( ) > 0 ) { v [ j ] . push_back ( arr [ i ] ) ; PartitionSub ( arr , i + 1 , N , K , nos , v ) ; v [ j ] . pop_back ( ) ; } else { v [ j ] . push_back ( arr [ i ] ) ; PartitionSub ( arr , i + 1 , N , K , nos + 1 , v ) ; v [ j ] . pop_back ( ) ; break ; } } } void partKSubsets ( int arr [ ] , int N , int K ) { vector < vector < int > > v ( K ) ; if ( K == 0 K > N ) { cout << " Not ▁ Possible " << endl ; } else { cout << " The ▁ Subset ▁ Combinations ▁ are : ▁ " << endl ; PartitionSub ( arr , 0 , N , K , 0 , v ) ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int K = 2 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; partKSubsets ( arr , N , K ) ; }
Count the number of Prime Cliques in an undirected graph | C ++ implementation to Count the number of Prime Cliques in an undirected graph ; Stores the vertices ; Graph ; Degree of the vertices ; To store the count of prime cliques ; Function to create Sieve to check primes ; false here indicates that it is not prime ; Condition if prime [ p ] is not changed , then it is a prime ; Update all multiples of p , set them to non - prime ; Function to check if the given set of vertices in store array is a clique or not ; Run a loop for all set of edges ; If any edge is missing ; Function to find the count of all the cliques having prime size ; Check if any vertices from i + 1 can be inserted ; Add the vertex to store ; If the graph is not a clique of size k then it cannot be a clique by adding another edge ; increase the count of prime cliques if the size of current clique is prime ; Check if another edge can be added ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 100 ; int store [ MAX ] , n ; int graph [ MAX ] [ MAX ] ; int d [ MAX ] ; int ans ; void SieveOfEratosthenes ( bool prime [ ] , int p_size ) { prime [ 0 ] = false ; prime [ 1 ] = false ; for ( int p = 2 ; p * p <= p_size ; p ++ ) { if ( prime [ p ] ) { for ( int i = p * 2 ; i <= p_size ; i += p ) prime [ i ] = false ; } } } bool is_clique ( int b ) { for ( int i = 1 ; i < b ; i ++ ) { for ( int j = i + 1 ; j < b ; j ++ ) if ( graph [ store [ i ] ] [ store [ j ] ] == 0 ) return false ; } return true ; } void primeCliques ( int i , int l , bool prime [ ] ) { for ( int j = i + 1 ; j <= n ; j ++ ) { store [ l ] = j ; if ( is_clique ( l + 1 ) ) { if ( prime [ l ] ) ans ++ ; primeCliques ( j , l + 1 , prime ) ; } } } int main ( ) { int edges [ ] [ 2 ] = { { 1 , 2 } , { 2 , 3 } , { 3 , 1 } , { 4 , 3 } , { 4 , 5 } , { 5 , 3 } } ; int size = sizeof ( edges ) / sizeof ( edges [ 0 ] ) ; n = 5 ; bool prime [ n + 1 ] ; memset ( prime , true , sizeof ( prime ) ) ; SieveOfEratosthenes ( prime , n + 1 ) ; for ( int i = 0 ; i < size ; i ++ ) { graph [ edges [ i ] [ 0 ] ] [ edges [ i ] [ 1 ] ] = 1 ; graph [ edges [ i ] [ 1 ] ] [ edges [ i ] [ 0 ] ] = 1 ; d [ edges [ i ] [ 0 ] ] ++ ; d [ edges [ i ] [ 1 ] ] ++ ; } ans = 0 ; primeCliques ( 0 , 1 , prime ) ; cout << ans << " STRNEWLINE " ; return 0 ; }
Construct a Doubly linked linked list from 2D Matrix | C ++ program to construct a Doubly linked linked list from 2D Matrix ; define dimension of matrix ; struct node of doubly linked list with four pointer next , prev , up , down ; function to create a new node ; function to construct the doubly linked list ; Create Node with value contain in matrix at index ( i , j ) ; Assign address of curr into the prev pointer of temp ; Assign address of curr into the up pointer of temp ; Recursive call for next pointer ; Recursive call for down pointer ; Return newly constructed node whose all four node connected at it 's appropriate position ; Function to construct the doubly linked list ; function call for construct the doubly linked list ; function for displaying doubly linked list data ; pointer to move right ; pointer to move down ; loop till node -> down is not NULL ; loop till node -> right is not NULL ; driver code ; initialise matrix
#include <iostream> NEW_LINE using namespace std ; #define dim  3 NEW_LINE struct Node { int data ; Node * next ; Node * prev ; Node * up ; Node * down ; } ; Node * createNode ( int data ) { Node * temp = new Node ( ) ; temp -> data = data ; temp -> next = NULL ; temp -> prev = NULL ; temp -> up = NULL ; temp -> down = NULL ; return temp ; } Node * constructDoublyListUtil ( int mtrx [ ] [ dim ] , int i , int j , Node * curr ) { if ( i >= dim j >= dim ) { return NULL ; } Node * temp = createNode ( mtrx [ i ] [ j ] ) ; temp -> prev = curr ; temp -> up = curr ; temp -> next = constructDoublyListUtil ( mtrx , i , j + 1 , temp ) ; temp -> down = constructDoublyListUtil ( mtrx , i + 1 , j , temp ) ; return temp ; } Node * constructDoublyList ( int mtrx [ ] [ dim ] ) { return constructDoublyListUtil ( mtrx , 0 , 0 , NULL ) ; } void display ( Node * head ) { Node * rPtr ; Node * dPtr = head ; while ( dPtr ) { rPtr = dPtr ; while ( rPtr ) { cout << rPtr -> data << " ▁ " ; rPtr = rPtr -> next ; } cout << " STRNEWLINE " ; dPtr = dPtr -> down ; } } int main ( ) { int mtrx [ dim ] [ dim ] = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; Node * list = constructDoublyList ( mtrx ) ; display ( list ) ; return 0 ; }
Count of exponential paths in a Binary Tree | C ++ program to find the count exponential paths in Binary Tree ; A Tree node ; Function to create a new node ; function to find x ; Take log10 of n ; Log ( n ) with base i ; Raising i to the power p ; function To check whether the given node equals to x ^ y for some y > 0 ; Take logx ( n ) with base x ; Utility function to count the exponent path in a given Binary tree ; Base Condition , when node pointer becomes null or node value is not a number of pow ( x , y ) ; Increment count when encounter leaf node ; Left recursive call save the value of count ; Right recursive call and return value of count ; function to count exponential paths ; Driver Code ; create Tree ; retrieve the value of x ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; struct Node * left , * right ; } ; Node * newNode ( int key ) { Node * temp = new Node ; temp -> key = key ; temp -> left = temp -> right = NULL ; return ( temp ) ; } int find_x ( int n ) { if ( n == 1 ) return 1 ; double num , den , p ; num = log10 ( n ) ; int x , no ; for ( int i = 2 ; i <= n ; i ++ ) { den = log10 ( i ) ; p = num / den ; no = ( int ) ( pow ( i , int ( p ) ) ) ; if ( abs ( no - n ) < 1e-6 ) { x = i ; break ; } } return x ; } bool is_key ( int n , int x ) { double p ; p = log10 ( n ) / log10 ( x ) ; int no = ( int ) ( pow ( x , int ( p ) ) ) ; if ( n == no ) return true ; return false ; } int evenPaths ( struct Node * node , int count , int x ) { if ( node == NULL || ! is_key ( node -> key , x ) ) { return count ; } if ( ! node -> left && ! node -> right ) { count ++ ; } count = evenPaths ( node -> left , count , x ) ; return evenPaths ( node -> right , count , x ) ; } int countExpPaths ( struct Node * node , int x ) { return evenPaths ( node , 0 , x ) ; } int main ( ) { Node * root = newNode ( 27 ) ; root -> left = newNode ( 9 ) ; root -> right = newNode ( 81 ) ; root -> left -> left = newNode ( 3 ) ; root -> left -> right = newNode ( 10 ) ; root -> right -> left = newNode ( 70 ) ; root -> right -> right = newNode ( 243 ) ; root -> right -> right -> left = newNode ( 81 ) ; root -> right -> right -> right = newNode ( 909 ) ; int x = find_x ( root -> key ) ; cout << countExpPaths ( root , x ) ; return 0 ; }
Number of pairs such that path between pairs has the two vertices A and B | C ++ program to find the number of pairs such that the path between every pair contains two given vertices ; Function to perform DFS on the given graph by fixing the a vertex ; To mark a particular vertex as visited ; Variable to store the count of the vertices which can be reached from a ; Performing the DFS by iterating over the visited array ; If the vertex is not visited and removing the vertex b ; Function to return the number of pairs such that path between any two pairs consists the given two vertices A and B ; Initializing the visited array and assigning it with 0 's ; Initially , the count of vertices is 0 ; Performing DFS by removing the vertex B ; Count the vertices which cannot be reached after removing the vertex B ; Again reinitializing the visited array ; Setting the count of vertices to 0 to perform the DFS again ; Performing the DFS by removing the vertex A ; Count the vertices which cannot be reached after removing the vertex A ; Multiplying both the vertices set ; Driver code ; Loop to store the graph
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int N = 1000001 ; int c , n , m , a , b ; void dfs ( int a , int b , vector < int > v [ ] , int vis [ ] ) { vis [ a ] = 1 ; c ++ ; for ( auto i : v [ a ] ) { if ( ! vis [ i ] && i != b ) dfs ( i , b , v , vis ) ; } } void Calculate ( vector < int > v [ ] ) { int vis [ n + 1 ] ; memset ( vis , 0 , sizeof ( vis ) ) ; c = 0 ; dfs ( a , b , v , vis ) ; int ans1 = n - c - 1 ; memset ( vis , 0 , sizeof ( vis ) ) ; c = 0 ; dfs ( b , a , v , vis ) ; int ans2 = n - c - 1 ; cout << ans1 * ans2 << " STRNEWLINE " ; } int main ( ) { n = 7 , m = 7 , a = 3 , b = 5 ; int edges [ ] [ 2 ] = { { 1 , 2 } , { 2 , 3 } , { 3 , 4 } , { 4 , 5 } , { 5 , 6 } , { 6 , 7 } , { 7 , 5 } } ; vector < int > v [ n + 1 ] ; for ( int i = 0 ; i < m ; i ++ ) { v [ edges [ i ] [ 0 ] ] . push_back ( edges [ i ] [ 1 ] ) ; v [ edges [ i ] [ 1 ] ] . push_back ( edges [ i ] [ 0 ] ) ; } Calculate ( v ) ; return 0 ; }
Travelling Salesman Problem implementation using BackTracking | C ++ implementation of the approach ; Function to find the minimum weight Hamiltonian Cycle ; If last node is reached and it has a link to the starting node i . e the source then keep the minimum value out of the total cost of traversal and " ans " Finally return to check for more possible values ; BACKTRACKING STEP Loop to traverse the adjacency list of currPos node and increasing the count by 1 and cost by graph [ currPos ] [ i ] value ; Mark as visited ; Mark ith node as unvisited ; Driver code ; n is the number of nodes i . e . V ; Boolean array to check if a node has been visited or not ; Mark 0 th node as visited ; Find the minimum weight Hamiltonian Cycle ; ans is the minimum weight Hamiltonian Cycle
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define V  4 NEW_LINE void tsp ( int graph [ ] [ V ] , vector < bool > & v , int currPos , int n , int count , int cost , int & ans ) { if ( count == n && graph [ currPos ] [ 0 ] ) { ans = min ( ans , cost + graph [ currPos ] [ 0 ] ) ; return ; } for ( int i = 0 ; i < n ; i ++ ) { if ( ! v [ i ] && graph [ currPos ] [ i ] ) { v [ i ] = true ; tsp ( graph , v , i , n , count + 1 , cost + graph [ currPos ] [ i ] , ans ) ; v [ i ] = false ; } } } ; int main ( ) { int n = 4 ; int graph [ ] [ V ] = { { 0 , 10 , 15 , 20 } , { 10 , 0 , 35 , 25 } , { 15 , 35 , 0 , 30 } , { 20 , 25 , 30 , 0 } } ; vector < bool > v ( n ) ; for ( int i = 0 ; i < n ; i ++ ) v [ i ] = false ; v [ 0 ] = true ; int ans = INT_MAX ; tsp ( graph , v , 0 , n , 1 , 0 , ans ) ; cout << ans ; return 0 ; }