# 格雷码(Gray Code) C语言 DFS版

Description

Gray code is an interesting code sequence and has many applications in computer science. No matter you have known it before or not, here are some introductions about its features:
(1) Gray code has 2^n unique elements;
(2) Each element contains n digits of 0 or 1;
(3) Each pair of adjacent elements has exactly one different digit.
For example, when n=2, one of the gray code sequence is: 00,01,11,10.
Now, the task is quite simple, given a positive integer n, generate the corresponding Gray code sequence.

Input

Input may contain multiple test cases. Each test case consists of one positive integer n(n<=16), Input is terminated by a case with n=0, which should not be processed.

Output

For each test case, output the corresponding Gray code sequence, one element per line. There may be multiple answers, any of them will be accepted. Please output a blank line after each test case.

Tips:注释很重要，很久以前的程序不加注释很容易看不懂…

```#include
#include

int n;
char s[17];

void dfs(int i)
{
if(i==n) printf("%s\n",s); //到达底部就输出
else
{
dfs(i+1); //深度优先搜索
if(s[i]=='0') s[i]='1';
else s[i]='0'; //把当前位逆转
dfs(i+1); //继续向下搜索
}
}

int main()
{
int i;
while(1)
{
scanf("%d",&n);
if(!n) break;
for(i=0;i<17;i++) s[i]='0';
s[n]='\0';
dfs(0);
printf("\n");
}
system("pause");
return 0;
}
```

### 网友最新评论 (6)

1. 看不懂递归的过程 可以解释一下么
4年前 (2018-06-07)回复
2. 绝对赞赞赞！！！！帮了我好大的忙！
Cathy7年前 (2015-05-08)回复
3. 里面的递归太高深了
霸气的雷公20129年前 (2013-04-04)回复
4. 我对格雷码的特点不是很了解，确实看不懂里面的递归。。。
L10年前 (2012-11-27)回复
5. 謝謝你的程式碼，讓我對遞迴有更深的瞭解。
monkey41310年前 (2012-03-29)回复
6. 好，不过对格雷码的特点不是很了解的人，对里面的递归看不懂
匿名13年前 (2009-03-13)回复