A backtracking approach to generate n bit Gray Codes

Given a number n, the task is to generate n bit Gray codes (generate bit patterns from 0 to 2^n-1 such that successive patterns differ by one bit)
Examples:

Input : 2 
Output : 0 1 3 2
Explanation : 
00 - 0
01 - 1
11 - 3
10 - 2

Input : 3 
Output : 0 1 3 2 6 7 5 4

We have discussed an approach in Generate n-bit Gray Codes

This article provides a backtracking approach to the same problem. Idea is that for each bit out of n bit we have a choice either we can ignore it or we can invert the bit so this means our gray sequence goes upto 2 ^ n for n bits. So we make two recursive calls for either inverting the bit or leaving the bit as it is.

C++



filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to find the gray sequence of n bits.
#include <iostream>
#include <vector>
using namespace std;
  
/* we have 2 choices for each of the n bits either we 
   can include i.e invert the bit or we can exclude the 
   bit i.e we can leave the number as it is. */
void grayCodeUtil(vector<int>& res, int n, int& num)
{
    // base case when we run out bits to process
    // we simply include it in gray code sequence.
    if (n == 0) {
        res.push_back(num);
        return;
    }
  
    // ignore the bit.
    grayCodeUtil(res, n - 1, num);
  
    // invert the bit.
    num = num ^ (1 << (n - 1));
    grayCodeUtil(res, n - 1, num);
}
  
// returns the vector containing the gray 
// code sequence of n bits.
vector<int> grayCodes(int n)
{
    vector<int> res;
  
    // num is passed by reference to keep
    // track of current code.
    int num = 0;
    grayCodeUtil(res, n, num);
  
    return res;
}
  
// Driver function.
int main()
{
    int n = 3;
    vector<int> code = grayCodes(n);
    for (int i = 0; i < code.size(); i++) 
        cout << code[i] << endl;    
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// JAVA program to find the gray sequence of n bits.
import java.util.*;
  
class GFG
{
  
static int num;
  
/* we have 2 choices for each of the n bits either we 
can include i.e invert the bit or we can exclude the 
bit i.e we can leave the number as it is. */
static void grayCodeUtil(Vector<Integer> res, int n)
{
    // base case when we run out bits to process
    // we simply include it in gray code sequence.
    if (n == 0)
    {
        res.add(num);
        return;
    }
  
    // ignore the bit.
    grayCodeUtil(res, n - 1);
  
    // invert the bit.
    num = num ^ (1 << (n - 1));
    grayCodeUtil(res, n - 1);
}
  
// returns the vector containing the gray 
// code sequence of n bits.
static Vector<Integer> grayCodes(int n)
{
    Vector<Integer> res = new Vector<Integer>();
  
    // num is passed by reference to keep
    // track of current code.
    num = 0;
    grayCodeUtil(res, n);
  
    return res;
}
  
// Driver function.
public static void main(String[] args)
{
    int n = 3;
    Vector<Integer> code = grayCodes(n);
    for (int i = 0; i < code.size(); i++) 
        System.out.print(code.get(i) +"\n"); 
}
}
  
// This code is contributed by Rajput-Ji

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to find the 
# gray sequence of n bits. 
  
""" we have 2 choices for each of the n bits 
either we can include i.e invert the bit or 
we can exclude the bit i.e we can leave 
the number as it is. """
def grayCodeUtil(res, n, num):
      
    # base case when we run out bits to process
    # we simply include it in gray code sequence. 
    if (n == 0):
        res.append(num[0])
        return
          
    # ignore the bit.
    grayCodeUtil(res, n - 1, num)
      
    # invert the bit. 
    num[0] = num[0] ^ (1 << (n - 1)) 
    grayCodeUtil(res, n - 1, num) 
      
# returns the vector containing the gray
# code sequence of n bits. 
def grayCodes(n):
    res = []
      
    # num is passed by reference to keep 
    # track of current code. 
    num = [0]
    grayCodeUtil(res, n, num) 
    return res 
  
# Driver Code
n = 3
code = grayCodes(n) 
for i in range(len(code)):
    print(code[i])
  
# This code is contributed by SHUBHAMSINGH10

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find the gray sequence of n bits.
using System;
using System.Collections.Generic;
  
class GFG
{
  
static int num;
  
/* we have 2 choices for each of the n bits either we 
can include i.e invert the bit or we can exclude the 
bit i.e we can leave the number as it is. */
static void grayCodeUtil(List<int> res, int n)
{
    // base case when we run out bits to process
    // we simply include it in gray code sequence.
    if (n == 0)
    {
        res.Add(num);
        return;
    }
  
    // ignore the bit.
    grayCodeUtil(res, n - 1);
  
    // invert the bit.
    num = num ^ (1 << (n - 1));
    grayCodeUtil(res, n - 1);
}
  
// returns the vector containing the gray 
// code sequence of n bits.
static List<int> grayCodes(int n)
{
    List<int> res = new List<int>();
  
    // num is passed by reference to keep
    // track of current code.
    num = 0;
    grayCodeUtil(res, n);
  
    return res;
}
  
// Driver function.
public static void Main(String[] args)
{
    int n = 3;
    List<int> code = grayCodes(n);
    for (int i = 0; i < code.Count; i++) 
        Console.Write(code[i] +"\n"); 
}
}
  
// This code is contributed by 29AjayKumar

chevron_right



Output:

0
1
3
2
6
7
5
4


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.