A backtracking approach to generate n bit Gray Codes ?

In this article, we will learn how to generate n-bit Gray codes using a backtracking approach in C. Gray code is a binary numeral system where successive values differ in only one bit. For n = 3 bits, the Gray code sequence is: 000, 001, 011, 010, 110, 111, 101, 100 (decimal: 0, 1, 3, 2, 6, 7, 5, 4).

Syntax

void generateGray(int arr[], int *index, int n, int num);

Algorithm

The backtracking algorithm works recursively −

generateGray(arr, index, n, num):
    if n = 0:
        arr[*index] = num
        (*index)++
        return
    generateGray(arr, index, n-1, num)
    num = num XOR (1 << (n-1))
    generateGray(arr, index, n-1, num)

How It Works

The algorithm generates Gray codes by making two recursive calls at each level. First, it generates codes with the current bit as 0, then flips the bit using XOR and generates codes with that bit as 1. This ensures adjacent codes differ by exactly one bit.

Gray Code Generation (n=2) 00 00 10 00 01 11 10

Example

#include <stdio.h>

void generateGray(int arr[], int *index, int n, int num) {
    if (n == 0) {
        arr[(*index)++] = num;
        return;
    }
    generateGray(arr, index, n - 1, num);
    num = num ^ (1 << (n - 1));
    generateGray(arr, index, n - 1, num);
}

void printGrayCodes(int n) {
    int totalCodes = 1 << n;
    int grayCode[totalCodes];
    int index = 0;
    
    generateGray(grayCode, &index, n, 0);
    
    printf("Gray codes for %d bits:<br>", n);
    for (int i = 0; i < totalCodes; i++) {
        printf("%d ", grayCode[i]);
    }
    printf("<br>");
}

int main() {
    int n = 3;
    printGrayCodes(n);
    return 0;
}
Gray codes for 3 bits:
0 1 3 2 6 7 5 4 

Key Points

  • The algorithm uses recursive backtracking to generate all possible Gray codes.
  • Time complexity: O(2^n) as we generate 2^n codes.
  • Space complexity: O(n) for recursion depth plus O(2^n) for storing results.
  • Each recursive call flips exactly one bit using XOR operation.

Conclusion

The backtracking approach efficiently generates n-bit Gray codes by recursively building the sequence. This method ensures that consecutive codes differ by exactly one bit, which is the fundamental property of Gray codes.

Updated on: 2026-03-15T10:56:27+05:30

557 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements