In this section we will see how we can generate the gray codes of n bits using backtracking approach? The n bit gray code is basically bit patterns from 0 to 2^n – 1 such that successive patterns differ by one bit. So for n = 2, the gray codes are (00, 01, 11, 10) and decimal equivalent is (0, 1, 3, 2). The program will generate the decimal equivalent of the gray code values.
Algorithm
generateGray(arr, n, num)
begin if n = 0, then insert num into arr return end if generateGray(arr, n-1, num) num := num XOR (1 bit left shift of n-1) generateGray(arr, n-1, num) end
Example
#include<iostream> #include<vector> using namespace std; void generateGray(vector<int>&arr, int n, int &num){ if(n==0){ arr.push_back(num); return; } generateGray(arr, n-1, num); num = num ^ (1 << (n-1)); generateGray(arr, n-1, num); } vector<int> gray(int n){ vector<int> arr; int num = 0; generateGray(arr, n, num); return arr; } main() { int n; cout << "Enter number of bits: "; cin >> n; vector<int> grayCode = gray(n); for(int i = 0; i<grayCode.size(); i++){ cout << grayCode[i] << endl; } }
Output
Enter number of bits: 3 0 1 3 2 6 7 5 4